Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs dynamic directive inside ngrepeat

Look at 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 can I write code, that p.dir will dynamically convert to a directive ?

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

like image 698
Igor S. Avatar asked Apr 17 '14 10:04

Igor S.


1 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 have to add terminal:true and priority: 1000. Check out Add directives from directive in AngularJS

like image 74
Khanh TO Avatar answered Nov 08 '22 05:11

Khanh TO