4

When there are multiple directives across multiple elements on a page, how does Angular's HTML compiler arrange the order for compiling?

Say I have the following markups, where alpha, beta, and gamma are custom Angular directives,

<html ng-app>
  <alpha><beta></beta></alpha>
  <gamma></gamma>
</html>

What's the order the compiler would work on them? Is it alpha => gamma => beta? Or is it alpha => beta => gamma?

To complicate things a little bit more, consider alpha directive's template has another custom directive, called foo. When would foo get compiled? After all of the above directives get compiled? Or right after alpha is compiled?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
tamakisquare
  • 16,659
  • 26
  • 88
  • 129

3 Answers3

3

I asked the same question in the AngularJS mailing list and Peter Bacon Darwin gave a great answer with a jsfiddle for demonstration. Link

tamakisquare
  • 16,659
  • 26
  • 88
  • 129
1

Regarding multiple directives on one element:

This is handled using the directive 'priority' property. From the docs: Once all directives for a given DOM element have been identified they are sorted by priority and their compile() functions are executed.

See http://docs.angularjs.org/guide/directive

Regarding directive compile order:

Angular will traverse the DOM - i.e. pick up the elements in the order they appear in the DOM tree. From the docs: Compile: traverse the DOM and collect all of the directives. The result is a linking function.

See http://docs.angularjs.org/guide/compiler

Alex Osborn
  • 9,831
  • 3
  • 33
  • 44
  • Alex - Thanks for your answer. Directive compilation is composed of two parts - Compiling function and linking function. What you said for directive compile order is only half of the story. I asked the same question in the AngularJS mailing list and Peter Bacon Darwin gave a great answer with a jsfiddle for demostration (see the accepted answer). – tamakisquare Feb 23 '13 at 19:45
0

The order of the linking and compiling functions is well described in the other answers and in the Angular documentation of the $compile function at https://docs.angularjs.org/api/ng/service/$compile:

  1. Compile and pre-link top-down (First parent, then children)
  2. Post-link the other way around
  3. Directives on the same element are treated by their priority attribute

In addition: 4. When using the templateUrl option in a directive, that directive will not compile until the template is loaded, but the compiler will continue compiling other directives. This will break the compiling/linking order described above.