In this section, we will see execution timing of directive controller and associated link function in action. I’m looking at the timing of directive’s controller and link functions. As the DOM is compiled by AngularJS, the directive controller and link function execute at different levels of the compile lifecycle. When AngularJS compiles the DOM, it walks down the DOM tree in a.
As it traverses the DOM, it instantiates the directive controllers. However, when it reaches to the bottom of a local DOM tree, it starts linking the directives in a bottom-up manner as it walks back up the branch. Below is the sample code which I have created for demo. Below is the sample snippet for the same.
And Corresponding HTML.
With the above change in place, below is the output.
And Corresponding Console messages.
As you can see in the above flow, for any directive first controller gets initialized top to bottom and then link function gets attached to it from bottom to top. Here, in this case as well. Below is the flow
Outer Controller –> Mid Controller –> Inner Controller –> Inner Link –> Mid Link. (1st Branch)
Second Mid Controller –> Second Mid Link (2nd Branch),
Outer Link.
I hope you would have liked today’s discussion. in coming section, we’ll delve further into minute details of directive’s flow. Till then stay tuned and Happy Coding.
Thanks,
Rahul Sahay
Happy coding