看一下例子:
- $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>
有关此指令如何工作的更多信息以及为什么我们必须添加terminal:true和priority:1000.请查看Add directives from directive in AngularJS