javascript – ngrepeat中的Angularjs动态指令

前端之家收集整理的这篇文章主要介绍了javascript – 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会动态转换为指令?

我的例子: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:true和priority:1000.请查看Add directives from directive in AngularJS

原文链接:https://www.f2er.com/js/150677.html

猜你在找的JavaScript相关文章