What is the difference between compile and link function in angularjs

  • compile function – use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive.

  • link function – use for registering DOM listeners (i.e., $watch expressions on the instance scope) as well as instance DOM manipulation (i.e., manipulation of iElement = individual instance element).
    It is executed after the template has been cloned. E.g., inside an <li ng-repeat…>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element.
    A $watch() allows a directive to be notified of instance scope property changes (an instance scope is associated with each instance), which allows the directive to render an updated instance value to the DOM — by copying content from the instance scope into the DOM.

Note that DOM transformations can be done in the compile function and/or the link function.

Most directives only need a link function, since most directives only deal with a specific DOM element instance (and its instance scope).

One way to help determine which to use: consider that the compile function does not receive a scope argument. (I’m purposely ignoring the transclude linking function argument, which receives a transcluded scope — this is rarely used.) So the compile function can’t do anything you would want to do that requires an (instance) scope — you can’t $watch any model/instance scope properties, you can’t manipulate the DOM using instance scope information, you can’t call functions defined on the instance scope, etc.

However, the compile function (like the link function) does have access to the attributes. So if your DOM manipulations don’t require the instance scope, you can use a compile function. Here’s an example of a directive that only uses a compile function, for those reasons. It examines the attributes, but it doesn’t need an instance scope to do its job.

Here’s an example of a directive that also only uses a compile function. The directive only needs to transform the template DOM, so a compile function can be used.

Another way to help determine which to use: if you don’t use the “element” parameter in the link function, then you probably don’t need a link function.

Since most directives have a link function, I’m not going to provide any examples — they should be very easy to find.

Note that if you need a compile function and a link function (or pre and post link functions), the compile function must return the link function(s) because the ‘link’ attribute is ignored if the ‘compile’ attribute is defined.

See also

Leave a Comment