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

时间:2021-11-19 15:11:43

The idea is that it should work as follows,

它的原理是,

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

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

I have a list of directives, that I need to loop through. The issue is, I can't hard code into the main directive because I need to add each custom directive one at a time.

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

1 个解决方案

#1


2  

Use the $compile service in a custom directive:

在自定义指令中使用$compile服务:

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));
  }
});

Usage:

用法:

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

The DEMO on PLNKR

演示在PLNKR

#1


2  

Use the $compile service in a custom directive:

在自定义指令中使用$compile服务:

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));
  }
});

Usage:

用法:

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

The DEMO on PLNKR

演示在PLNKR