【问题标题】:Angularjs dynamic directive inside ngrepeatngrepeat 中的 Angularjs 动态指令
【发布时间】:2014-06-01 13:33:21
【问题描述】:

看例子:

$scope.fields = [{
    name: 'Email',
    dir : "abc"
}, {
    name: 'List',
   dir : "ddd"
}];

app.directive('abc', function () {});
app.directive('ddd', function () {});

<table class="table table-hover">
        <tr ng-repeat="p in fields">
          <input {{p.dir}} ngmodel="p" />
        </tr>
    </table>

如何编写代码,p.dir 将动态转换为 directive

我的例子:hhttp://jsbin.com/vejib/1/edit

【问题讨论】:

  • 你真的需要一个指令吗?你能换成&lt;td&gt;dddd: {{p.name}}&lt;/td&gt;&lt;td&gt;ddd: {{p.age}}&lt;/td&gt;吗?
  • @RuslanIsmagilov 这与视觉无关。 Eash 指令有它自己的业务逻辑。我想用自定义业务逻辑动态构建表单。
  • 我想我有类似的问题,你需要将指令范围设置为隔离。检查文档docs.angularjs.org/guide/directive

标签: javascript angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

你可以这样说:

<input {{p.dir}} ngmodel="p" />

也在指令中。您可以在 JavaScript 中构造这个 HTML 字符串并将其附加到 DOM。您还需要使用 $compile 服务编译生成的元素,以便编译动态指令。

一些虚拟示例代码(未经测试,但应该看起来像这样):

app.directive('dynamicInput', function($compile){
return {
    link: function(scope, element){
        var htmlString = '<input ' + scope.field.dir + ' ng-model="p"/>';
        element.replaceWith(htmlString);
        $compile(angular.element(element))(scope);
    }
}

});

更多信息here

【讨论】:

    【解决方案2】:

    试试这个指令:

    app.directive('dynamicDirective',function($compile){
      return {
          restrict: 'A',
          replace: false, 
          terminal: true, 
          priority: 1000, 
          link:function(scope,element,attrs){
    
            element.attr(scope.$eval(attrs.dynamicDirective),"");//add dynamic directive
    
            element.removeAttr("dynamic-directive"); //remove the attribute to avoid indefinite loop
            element.removeAttr("data-dynamic-directive");
    
            $compile(element)(scope);
          }
      };
    });
    

    使用它:

    <table class="table table-hover">
       <tr ng-repeat="p in people">
          <td dynamic-directive="p.dir" blah="p"></td>
       </tr>
    </table>
    

    DEMO

    有关此指令如何工作以及为什么我们必须添加 terminal:truepriority: 1000 的更多信息。查看Add directives from directive in AngularJS

    【讨论】:

    • 谢谢。我认为 Angular 有类似的内置功能。显然不是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2016-04-18
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多