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!

1
  • 1
    Is your directive restricted to an attribute? Have you tried class? Commented Jul 18, 2014 at 13:32

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.