Angularjs dynamic directive inside ngrepeat

Take a look at an example:

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

How to write code that p.dir will be dynamically converted to directive ?

My example: hhttp: //jsbin.com/vejib/1/edit

+6
source share
2 answers

Try this directive:

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

Use it:

 <table class="table table-hover"> <tr ng-repeat="p in people"> <td dynamic-directive="p.dir" blah="p"></td> </tr> </table> 

Demo

For more information on how this directive works, and why we should add a terminal: true and priority: 1000 . Go to Add Directives from Directives in AngularJS

+10
source

You can put this:

 <input {{p.dir}} ngmodel="p" /> 

also in the directive. You can build this HTML string in JavaScript and attach it to the DOM. And you will also need to compile the resulting element using the $ compilation service so that the dynamic directives are compiled.

Some kind of dummy code example (not tested, but should look something like this):

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

});

More details here .

0
source

All Articles