1
我試圖改變使用Angular和TypeScript的內聯SVG中的屬性的填充顏色。這個想法是,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);
這裏是一個Plunker與打字稿和遵守的JavaScript。
編輯 所以我想通了,如何做到這一點,但它仍然是不優雅,因爲範圍的名稱是硬編碼。我願意提供如何解耦爲兩個的建議。 (Plunker也更新)
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)
})
}
}
我們應該在演示中看到什麼?圓似乎改變 – charlietfl
中間的一個三角形,所有的文字也應該改變,除了圓 – jsexauer