2017-05-16 79 views
2

的想法是,它應該工作如下,如何將指令作爲屬性傳遞給另一個指令? AngularJS

//This is pseudo code: 
directives = [directive1, directive2, directive3] 
<ng-repeat directive in directives> 
    <main-directive attribute = "{{directive}}"> 

    </main-directive> 
</ng-repeat> 

我的指令列表中,我通過需要循環。問題是,我不能硬編碼到主指令,因爲我需要一次添加一個自定義指令。

回答

2

使用$compile service在自定義指令:

app.directive("dynamicComponent", function($compile) { 
    return { 
    link: postLink 
    }; 
    function postLink(scope, elem, attrs) { 
    var comp = scope.$eval(attrs.componentName); 
    var html = ` 
     <${comp}> 
     </${comp}> 
    `; 
    var linkFn = $compile(html); 
    elem.append(linkFn(scope)); 
    } 
}); 

用法:

<div ng-repeat="name in ['comp-a','comp-b']"> 
    <dynamic-component component-name="name"> 
    </dynamic-component> 
</div> 

DEMO on PLNKR

+0

哇感謝你的幫助。 – Gregborrelly

相關問題