Menu

Filip Zawada

👨🏻‍💻 iOS tinkerer

How I tackled directive’s LifeCycle in AngularJS

Proper usage of compile, link and controller may cause a headache in Angular.
If you’re still struggling with – despite good answers – choosing the right one, that’s a sign you need to familiarize yourself with a Directive LifeCycle.

What functions are invoked in following directive?

Yes – even for such a simple directive a full LifeCycle is triggered. However – in this case the only function you need is the link. Compile, controller and preLink are practically useless. That leads to the second question:

Why do we need to have a controller?

To answer that let’s have a look on a directive construction life-cycle diagram:
diagram

On the above diagram you can see an order in which directives are created. It happens twice, first the DOM is traversed and all tags are compiled. In the second iteration controllers and link functions are called.

As you see <b> link function is called before <a>’s link – that means <b> can’t retrieve any information/configuration from <a> at this point. As a solution for this a controller is created before directive is fully initialized. Thanks to this, <b> can access <a> controller, even though <a> hasn’t yet finished creation process. So to sum up: Controllers allow directives talk to each other before they get fully initialized.

Why do we need a compile function?

For optimization purposes. Directives such as ng-repeat compiles repeated elements first, and then just clone. After cloning only controller and link function is called. So if you can, try to put stuff into compile function, so it’s not repeated when not necessary.

Comments

Jay Kan says:

Hey Filip,

Great post on explaining the order of execution from compile, controller & link functions. The diagram you have above illustrated the lifecycle of a directive, and I was wondering during the compile phase, shouldn’t be aCompile -> bCompile -> cCompile, aController -> bController -> cController, cLink -> bLink -> aLink

Gianluca says:

Very nice diagram you have there, I wish you could provide more diagrams like that to explain mechanisms like the binding of an attribute value inside a directive.

Chris O'Neil says:

Excellent! The directive lifecycle was so difficult to understand until now. I have used this at work to help explain (or more often debug) directives. An interesting note is the consequence of using template vs templateURL in which templateURL has the consequence of fetching the template asynchronously which can wreak havoc on the lifecycle

[…] How I tackled directive’s LifeCycle in AngularJS | Filip Zawada21.10.2014 – Proper usage of compile, link and controller may cause a headache in Angular. If you’re still struggling with – despite good answers – choosing … […]

Leave a Reply to Gianluca Cancel reply

Blue Captcha Image
Refresh

*