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,059
  • 12
  • 61
  • 91

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
  • 21,800
  • 20
  • 63
  • 83
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.

pixelbits
  • 50,631
  • 15
  • 93
  • 132