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:

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.