繁体   English   中英

ngrepeat中的Angularjs动态指令

[英]Angularjs dynamic directive inside ngrepeat

看一下例子:

$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

试试这个指令:

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 查看AngularJS中指令的Add指令

你可以这样说:

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

});

更多信息在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM