我的视图上有几个按钮,每个按钮都有三种状态:活动、非活动和悬停。这些将显示为图像。我有FooController:
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属性的类):
interface IFooScope extends ng.IScope {
design: FooDesign;
setUnitType(unitType: UnitType);
getUnitTypeImageUrl(unitType: UnitType);
} 我想有一个指令,它有像这样的html模板:
<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)。
我的指令是这样的:
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个不同的按钮(同时不可见,取决于之前的选择),所以这将是一团混乱,我想在获取正确的图像时使用枚举器。
我有点受困于此,所以欢迎每一项帮助。
发布于 2015-08-05 14:50:25
我抛弃了IFooScope,把它变成了一项服务,这样就不会混淆作用域了。此外,由于指令的作用域中有unitType (带有=),因此函数参数中不需要unitType,因为现在(当IFooScope不再存在时) scope.unitType可以访问它们。
https://stackoverflow.com/questions/31785358
复制相似问题