Link Function In AngularJS

Introduction

What are compile & link Options in Custom directives?

Understanding the compile vs. link option is one of the more advanced topics across AngularJS, and it gives us a feel for how Angular actually works. Out of both the functions the link function is used very often. Basically both are mutually exclusive i.e. if both the options are set then compile will overwrite the link functions defined. The concept of compile and link comes from C language, where you first compile the code and then link it to actually execute it. The process is very much similar in AngularJS as well.

Compile: It traverses the DOM and collects all of the directives and deals with transforming the template DOM. The result is a linking function.

Link: The link function deals with linking scope to the DOM.

Using Code for Compile

While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre & post function.

If compile is defined as defined below then it will override the link function as shown in below example.

Code

Using Code for Pre & Post Link

While defining a custom directive we have the option called“link” against which either we can define a single function or we have the option to assign an object in which we can define further two functions i.e. Pre-link and Post- link functions.

If only a single function is defined against link option that will be same as Post link function.

Both Pre & Post link function have the same syntax as defined below but the only difference is the order in which they gets executed.

Link example,

Post Link

In above example we are defining a function against link option which will get executed before linking scope and the template.

Pre & Post functions examples:

Defining only Post,

Defining only Post

Defining post is same as the link option defined with a normal function as defined in above link example.

Defining Pre & Post

The signature is of the pre-link function is same as that of a post-link. The only difference between the pre-link and a post-link is the order they gets executed.

Defining Pre and post

In above example there is a directive defined with name parentDir1 which is having child directive called child1 and both are defined using post / link functions due to which the output shows that scope of parent is unable to be accessed in child scope due to which name of parent is printed as undefined.

And to this problem the solution is Pre-link function which is shown in above example with parentDir2 which is having child directive called child2 and parent is defined with pre-link function and child is defined with post link function.

Below is the output of above example,
output

Read more articles on AngularJS: