【发布时间】:2015-10-25 10:42:14
【问题描述】:
我的视图上有几个按钮,每个按钮都有三种状态:活动、非活动、悬停。这些显示为图像。 我有 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 = 毫米,则该按钮具有活动图像(例如 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 个不同的按钮(同时不可见,取决于之前的选择)所以这会很混乱,我想在获取正确的时候使用枚举器图片。
我有点坚持这一点,所以欢迎每一个帮助。
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope typescript