Angularjs dynamic directive inside ngrepeat

耗尽温柔 提交于 2019-11-30 20:24:38
Khanh TO

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

You could put this:

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

also in a directive. You could construct this HTML string in JavaScript and attach it to the DOM. And you would also need to compile the resulting element using the $compile service, so that the dynamic directives will be compiled.

Some dummy sample code (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 info here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!