Transclusion: compilation sequence

AngularJS compilation sequence becomes quite complicated when view is built with use of many transcluding directives. To understand this complexity I have made little research and here is the output.


Explanation below is based on AngularJS directive compilation sequence decomposition I have made in other post – Directive Compilation in AngularJS – step-by-step.

Compile many directives on single element

Assuming our transcluding directive has priority X the sequence of compilation will complicate a bit and split into two parts:

  1. Before exclusion:
    • template and compile of all other directives
    • compile of our directive (template is ignored)
    • pre-link functions (of ones with priority HIGHER than or equal to X) from higher to lower priority
    • post-link functions (of ones with priority HIGHER than or equal to X) in reverse order
    • controllers are invoked just before linking
  2. After inclusion:
    • pre-link functions (of ones with priority LOWER than X) from higher to lower priority
    • post-link functions (of ones with priority LOWER than X) in reverse order
    • controllers are invoked just before linking

And if we had 3 directives with priorities 100, 0 and -100, and our directive would be the middle one (X = 0) the compilation timeline may look like this:

Multi-Directive Transcluded Tag Compilation

Multi-Directive Transcluded Tag Compilation

ALL the templating is done quite normally – the only exception is that trancluding directive compile function is invoked last and template is ignored. The main difference from regular flow is blocking lower priority link functions and controllers which are invoked only while cloning original element.

And the demo fiddle: jsfiddle.net/ulfryk/9z0jfcc3

Compile many directives on nested elements

As in regular compilation, order of directives nested inside transcluding one is similar to that based on priority – the deeper the element nested, the later it is compiled. Nested elements’ templates and compile functions go before transclusion but controllers are instantiated and linking functions are called after inclusion.

Let’s consider 3 nested dives with topmost as transcluded one – timeline looks like this:

Nested Transcluded Directives Compilation

Nested Transcluded Directives Compilation

Everything happens as expected – create whole DOM tree inside element, hide it and finally link all inner content when including clones back.

And the demo fiddle: jsfiddle.net/ulfryk/eps5m4ow


Conclusion

This knowledge may seem to be a little redundant… But it gives developer full control over his widgets and improves design process of custom directives and application views.

Further Reading