1

I'm using AngularJS and am currently loading includes based on a variable like:

<div ng-include="'app/views/' + field.fieldType + '.tpl.html'"></div>

would it be possible to load directives similarly ( key off a variable name in the template )? Something like:

<div my-directive-{{field.fieldType}} />

Thanks!

amcdnl
  • 8,470
  • 12
  • 63
  • 99

2 Answers2

2

Sure, you can do it a little something like this.

.directive('myDirective',function(){
  return {
    link: function(scope,elem,attrs) {
      var directiveName = attrs['my-directive'];
      var directive = angular.element(document.createElement(directiveName));
      var el = $compile( directive )( scope );

      angular.element(document.body).append(directive);

    }
  }
});

With info from Insert directive programmatically angular

Community
  • 1
  • 1
Code Whisperer
  • 22,959
  • 20
  • 67
  • 85
0

It is possible, but I would recommend the following instead (as the Angular way):

<div my-directive field-type="field.fieldType" />

The dangers with re-compiling a directive to achieve the same thing are not worth the risk/effort IMO.

Michael Kang
  • 52,003
  • 16
  • 103
  • 135