Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When shall we use `preLink` of directive's compile function?

The compile function of angularjs' directive has two functions: preLink and postLink.

Pre-linking function

Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking.

Post-linking function

Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.

It tells what we should not do in preLink, I wonder what and when should I use preLink? For most of time I just used postLink. Is there any case that we must use it?

like image 326
Freewind Avatar asked Mar 08 '13 15:03

Freewind


People also ask

What is Prelink and Postlink in AngularJS?

Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Post-linking function Executed after the child elements are linked.

What does$ compile do in AngularJS?

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

What is compile and link in AngularJS?

Compile function: It is used for template DOM Manipulation and collect all of the directives. Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.

How directives are compiled?

Each directive's compile function is only called once, when Angular bootstraps. Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding. The <my-raw> directive will render a particular set of DOM markup.


1 Answers

You need almost never use preLink. Viable cases for it are when you need to manipulate data in scope, but not the DOM, before link functions (also of other directives) are executed.

As jacob commented, you can always do that from a controller too, but sometimes it's more appropriate to have the code in the directive itself.

There is an excellent article about how directives work where linking order is explained well to: http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/

If you need a good example of why pre-linking is sometimes necessary, I recommend you look at the code of angular directives themselves. For example https://github.com/angular/angular.js/blob/master/src/ng/directive/ngModel.js

like image 63
iwein Avatar answered Sep 21 '22 07:09

iwein