amcdnl
amcdnl

Reputation: 8638

AngularJS dynamic directive loading

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!

Upvotes: 1

Views: 153

Answers (2)

Michael Kang
Michael Kang

Reputation: 52837

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.

Upvotes: 0

Code Whisperer
Code Whisperer

Reputation: 23652

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

Upvotes: 2

Related Questions