首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带Typescirpt的Angular指令作用域

带Typescirpt的Angular指令作用域
EN

Stack Overflow用户
提问于 2015-08-03 18:49:23
回答 1查看 72关注 0票数 0

我的视图上有几个按钮,每个按钮都有三种状态:活动、非活动和悬停。这些将显示为图像。我有FooController:

代码语言:javascript
复制
foo.controller("FooController", function($scope: IFooScope) {
    // Tell the view about the classes in the app
    this.UnitType = UnitType;
    this.ImageType = ImageType;
    $scope.design = new FooDesign();
}); 

和一个接口(FooDesign只是一个具有unitType属性的类):

代码语言:javascript
复制
interface IFooScope extends ng.IScope { 
    design: FooDesign;

    setUnitType(unitType: UnitType);
    getUnitTypeImageUrl(unitType: UnitType);   
} 

我想有一个指令,它有像这样的html模板:

代码语言:javascript
复制
<div class="unit-type-button">
    <unit-type-image unit-type="UnitType.Millimeters">
    </unit-type-image>
</div>

<div class="unit-type-button">
    <unit-type-image unit-type="UnitType.Inches">
    </unit-type-image>
</div>

在scope.design中有一个unitType属性,单击这些按钮时必须更改该属性。因此,如果scope.design.unitType =eg,则该按钮具有活动图像(例如,unit_type_millimeters_active.png)和其他按钮具有非活动图像(例如,unit_type_inches_inactive.png),两者也都有悬停图像(例如unit_type_millimeters_hover.png)。

我的指令是这样的:

代码语言:javascript
复制
class UnitTypeImage implements ng.IDirective {
    constructor(private imageService: ImageService) { }

    restrict = "E";
    replace = true;
    template = '<img ng-click=setUnitType(unitType) src="{{getUnitTypeImageUrl(unitType)}}"/>';
    /*scope = {
        unitType: '=';
    };*/

    link = (scope: IFooScope, element, attrs) => {
        scope.setUnitType = function (unitType: UnitType) {
            scope.design.unitType = unitType;
        }

        scope.getUnitTypeImageUrl = function (unitType: UnitType) {
            return (unitType === scope.design.unitType) ? imageService.getUnitTypeImage(unitType, ImageType.Active) : imageService.getUnitTypeImage(unitType, ImageType.Inactive);
        }
    }

    static factory(): ng.IDirectiveFactory {
        var directive = (imageService: ImageService) => new UnitTypeImage(imageService);
        directive.$inject = ['imageService'];
        return directive;
    }
}
foo.directive('unitTypeImage', UnitTypeImage.factory());

如果我在指令中取消对作用域的注释,那么scope.design就是未定义的。如果我将其注释掉,那么每个函数参数的unitType都是未定义的。

此外,我还没有在这里包括悬停图像功能,我不确定如何做。一种选择是这样的:http://jsfiddle.net/ook3a8Lz/,但我在视图中有大约100个不同的按钮(同时不可见,取决于之前的选择),所以这将是一团混乱,我想在获取正确的图像时使用枚举器。

我有点受困于此,所以欢迎每一项帮助。

EN

回答 1

Stack Overflow用户

发布于 2015-08-05 14:50:25

我抛弃了IFooScope,把它变成了一项服务,这样就不会混淆作用域了。此外,由于指令的作用域中有unitType (带有=),因此函数参数中不需要unitType,因为现在(当IFooScope不再存在时) scope.unitType可以访问它们。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31785358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档