2016-07-02 93 views
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) 
     }) 
    } 
} 
+0

我們應該在演示中看到什麼?圓似乎改變 – charlietfl

+0

中間的一個三角形,所有的文字也應該改變,除了圓 – jsexauer

回答

1

將控制器與指令監視表達式分離的常見做法是改爲觀察指定的屬性。

取而代之的是以下內容:

JS:

scope.$watch('vm.fill', function (fill) { 
    attrs.$set('fill', fill); 
}); 

HTML:

<text ta="1">Text</text> 

你應該有:

JS:

scope.$watch(attrs.ta, (fill: string): void => { 
    attrs.$set('fill', fill); 
}); 

HTML:

<text ta="vm.fill">Text</text> 

這種做法可確保您的指令是更具可擴展性,因爲vm.fill監視表達式不綁定到向鏈路功能,而是通過角模板,而不是傳遞到指令。 Here is an updated plunkr

相關問題