PU$]-[KAR's

… Every drop has ability to survive .

Writing a Directive ….. link or controller ?

Leave a comment

Hey Guys,

As we know ‘Directive’ is a key for building an angularJS application. Its nothing without ‘Directives’. So here we can have a quick look at how to write a directive more on that what to use ‘link’ or ‘controller’? Otherwise confusion in choosing ‘link’ or ‘controller’ … then ‘Directive’ is just like a ‘Black-Box’.

So what is difference between ‘link’ & ‘controller’?

To understand this first we need to understand compilation process for directive. Consider a small application with nested directive. say ‘parent’ is a container and it has ‘Directive1’ which contains ‘ChildDirective’. So if we go through AngularJS doc. The sequence is as per following.
1. Parent container will get compile.
2. Directive1 will get compile.
3. ChildDirective will get compile.
4. Parent controller will get invoked
5. Parent Pre-link invoked.
6. Directive1 controller will get invoked.
7. Directive1 Pre-link invoked.
8. ChildDirective controller will get invoked.
9. ChildDirective Pre-link invoked.
10. ChildDirective Post-link invoked.
11. Directive1 Post-link invoked.
12. Parent container Post-link invoked.

So if you observed here order of invoking of ‘Post-Link’ is reversed and it is exactly what we were looking for. A ‘link’ function inside directive acts at ‘post-link’. where as ‘pre-link’ is rarely used. It means all child directives link functions get executed before the parent functions link functions.

So now consider a scenario where ‘Directive1’ want to have DOM manipulation of any element from ‘ChildDirective’

Now if we tried to have such ‘DOM’ manipulation inside ‘controller’ of ‘Direcive1’ it won’t be carried out because controller of ‘Directive1’ will get executed first than ‘post-link’ of ‘ChildDirective’.

So In such cases if we handle DOM manipulation inside ‘link’ of ‘Directive1’ then it will get executed. So over all its adivisable to have DOM manipulation inside ‘link’ function.

So Where we can use controller?
Stuff like using one directives controller in another i.e. assigning value in parent Directive (can be done in controller) and accessing it in child one can be done using controller. Because if you remember controller is acts like constructor more or less. So assigning default value is the main purpose of controller.

In short:

We can have a one quick question to our self weather we want it before compile or after compile. as controller as acts as constructor we can judge that whatever we can have before compile we can make it in ‘controller’ and things like ‘DOM’ manipulation which needs to complete compilation process can be carried out in ‘link’

Leave a comment