我试图改变属性的填充颜色在一个在线的SVG使用角和TypeScript。这个想法是,SVG有一个"TA“属性;任何带有这些"TA”属性之一的svg元素,我都希望更改填充颜色,以便从下拉列表中绑定到用户定义的颜色。但是,我很难弄清楚如何将这个属性更改为动态绑定。
我就是这么做的:
export class TaDirective implements ng.IDirective {
static create_instance() : ng.IDirective {
return new TaDirective();
}
constructor(){
}
public bindToController = true;
public controllerAs = "ctrl";
public scope = { name: '=' };
public compile(element: ng.IAugmentedJQuery, attrs: ng.IAttributes, transclude: ng.ITranscludeFunction) {
var ta = attrs.$attr["ta"] as string
var ele = element[0];
attrs.$set
// Make all visable (works as expected)
attrs.$set('visibility', "visible")
// Attempt to bind to the controller's fill
attrs.$set('fill', "{{ ctrl.fill }}")
//attrs.$set('fill', 'cyan') // Verify idea works
}
public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, controller: any, transclude: ng.ITranscludeFunction) {
//Tried code here
}
public controller(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes){
// Tried code here
}
}
app.directive('ta', TaDirective.create_instance);这里是一个带有TypeScript和已编译JavaScript的JavaScript。
编辑,所以我想出了如何做,但它仍然不优雅,因为作用域的名称是硬编码的。我对如何将两者解耦的建议持开放态度。(柱塞也更新)
export class TaDirective implements ng.IDirective {
static create_instance() : ng.IDirective {
return new TaDirective();
}
constructor(){
}
public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, controller: any, transclude: ng.ITranscludeFunction) {
var ta = attrs.$attr["ta"] as string
var ele = element[0];
// Make all visable
attrs.$set('visibility', "visible")
// Attempt to bind to the controller's fill
scope.$watch('vm.fill', function(newFill) {
attrs.$set('fill', newFill)
})
}
}发布于 2016-07-04 09:43:18
将控制器与指令监视表达式解耦的一个常见做法是监视指定的属性。
而不是采取以下措施:
联署材料:
scope.$watch('vm.fill', function (fill) {
attrs.$set('fill', fill);
});HTML:
<text ta="1">Text</text>你应该:
联署材料:
scope.$watch(attrs.ta, (fill: string): void => {
attrs.$set('fill', fill);
});HTML:
<text ta="vm.fill">Text</text>此实践确保您的指令具有更大的可伸缩性,因为vm.fill监视表达式不绑定到指令链接函数,而是通过角模板传递到指令中。下面是一个更新的plunkr。
https://stackoverflow.com/questions/38164042
复制相似问题