difference between Link and Compile in angularJS

Compile function:

During compile phase Angular compiles your directive. this function is called only once for each references to the directive. Eg. You are using your custom directive to ProductInfo which shows specific details of Product like Product name, Product price, Product maker etc. then your custom directive will have to look up the element it is attached to, extract the html content that it is attached to and create a template function.

The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.

In sort, Compile function is used for template DOM manipulation and to collect all the directive attached to the main directive.

Link function:

In this phase attach the $scope to the linking function and it should return you the attached html. As directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the $scope attached to it. Whatever code you write in the linking function its generally the post-link function. It is a callback that gets called after the linking function has linked the $scope with the template.

In sort, It is used for registering DOM listeners as well as instance DOM manipulation and is executed and the template has been cloned.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s