ngrepeat 中的 Angularjs 动态指令 [英] Angularjs dynamic directive inside ngrepeat

查看:29
本文介绍了ngrepeat 中的 Angularjs 动态指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看例子:

$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 ?

How can I write code, that p.dir will dynamically convert to a directive ?

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

My example: 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>

演示

有关此指令如何工作以及为什么我们必须添加 terminal:truepriority: 1000 的更多信息.查看 从 AngularJS 中的指令添加指令

For more information on how this directive works and why we have to add terminal:true and priority: 1000. Check out Add directives from directive in AngularJS

这篇关于ngrepeat 中的 Angularjs 动态指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆