ngrepeat中的Angularjs动态指令

时间:2014-04-17 10:18:15

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

看一下例子:

$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

2 个答案:

答案 0 :(得分:10)

尝试此指令:

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

有关此指令如何运作的详情以及我们必须添加终端:true 优先级:1000 的原因。查看Add directives from directive in AngularJS

答案 1 :(得分:0)

你可以这样说:

<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

相关问题