user2167582
user2167582

Reputation: 6388

how to manually compile templates twice or more

I want to compile an angular directive first to append attributes and then to compile the code again as other directives. Is there anyway for me to perhaps use compile: pre post or something to compile this

attribute-append to directive to Parent Directive templates?

Upvotes: 3

Views: 7313

Answers (1)

Eduard Gamonal
Eduard Gamonal

Reputation: 8031

let's say you have a directive <foo></foo> (restrict: 'E'). You want to add attributes dynamically (~ modify the original DOM, not the template), which should be done in the $compile step of the directive. After adding the attributes, to make angularjs realise if there is any new directive that can be triggered, you have to compile the new element. that's what ng-include does, for example. it includes elements in the DOM and compiles them so new directives can be used.

directive foo:

compile: function ($tElement, $tAttrs) {
  var el = $tElement[0];
  el.setAttribute('bar', 'newFancyValue');
  return function (scope, element, attrs) {
     // you can even append html elements here, for example the template
     element.append("<book></book>");
     $compile(element)(scope);
  };
}

and directive bar (with restrict: 'A') can have whatever code you want.

This is a related question you might want to read as well A general directive with a specific type (UI components inheritance)

look at the transclude function in the docs to see how to add previous inner elements of foo in book

Upvotes: 6

Related Questions