3

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?

user2167582
  • 5,986
  • 13
  • 64
  • 121

1 Answers1

6

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

Community
  • 1
  • 1
Eduard Gamonal
  • 8,023
  • 5
  • 41
  • 46
  • what if your 'foo' directive is restrict 'A'? it seems in this case the compile loops forever.. – Sterling Camden Oct 10 '13 at 21:24
  • yeah probably, because after compiling it, angular finds again the attribute that triggered the directive, which makes it compile it again and again. I guess you can remove the attribute in the compile function and return the link function only if the attribute existed. similar problem http://stackoverflow.com/questions/15929386/a-general-directive-with-a-specific-type-ui-components-inheritance – Eduard Gamonal Oct 11 '13 at 07:30
  • Any idea why the first parameter to compile `$tElement` is an array and not an element, thus requiring `var el = $tElement[0];`. Most examples treat it as a single object, but like the OP, I'm getting an array. – Izhaki Jul 02 '14 at 14:39