如何将指令作为属性传递给另一个指令? AngularJS

时间:2017-05-16 16:53:02

标签: angularjs angularjs-directive

这个想法是它应该如下工作,

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

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

我有一个指令列表,我需要循环。问题是,我不能硬编码到主指令中,因为我需要一次添加一个自定义指令。

1 个答案:

答案 0 :(得分: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