The compile and link functions in ANGULARJS directives complement

Source: Internet
Author: User

Usually when you use the instructions in Ng, the link function is the most linked property, the following article will tell you complie,pre-link,post-link usage and differences.

The instructions in the Angularjs are magical, allowing you to create very semantic and highly reusable components that can be understood as pioneers of the Web Component.

There are many articles about how to use the instructions on the Internet and related books, compared with each other, very few introduce the difference between compile and link, let alone pre-link and Post-link.

Most tutorials simply say that compile will be used within NG, and it is recommended that you use only the link attribute, which is the case for most instructions.

This is very unfortunate, because the correct understanding of the differences in these functions will improve your understanding of the mechanism of NG's internal operation and help you develop better custom directives.

So come along with me to see what these functions are and when they should be used in the next step.

This article assumes that you have a certain understanding of the instructions, and if not, it is strongly recommended that you take a look at this article Angularjs Developer Guide sections on Directives

How is the instruction handled in NG?

Before starting the analysis, let's look at how the instructions are handled in NG.

When a browser renders a page, it essentially reads the HTML identifier, then builds the DOM node and broadcasts an event to us when the DOM tree is created.

When you load NG application code using the script tag in the page, Ng listens to the DOM completion event above to find the element with the Ng-app attribute.

When such an element is found, Ng begins to process the DOM at the beginning of the element, so if Ng-app is added to the HTML element, NG will begin processing the DOM from the HTML element.

Starting from this starting point, Ng begins to recursively find all the child elements inside, conforming to the rules of instruction defined in the application.

How NG handles a directive is actually dependent on the object's properties when it is defined, you can define a compile or a link function, or use the Pre-Link and Post-link functions instead of link.

So what are the differences between these functions? Why use it? And when to use it?

Take these questions and follow me through the puzzle.

A section of code

To explain the differences between these functions, I'll use a simple and easy-to-understand example

1. If you have any questions, please don't hesitate to add your comments below.

Look at the following HTML tag code

Copy CodeThe code is as follows:
<level-one>
<level-two>
<level-three>
Hello
</level-three>
</level-two>
</level-one>

And then a JS code.

Copy CodeThe code is as follows:
var app = Angular.module (' Plunker ', []);

function createdirective (name) {
return function () {
return {
Restrict: ' E ',
Compile:function (TElem, tattrs) {
Console.log (name + ': Compile ');
return {
Pre:function (Scope, Ielem, iattrs) {
Console.log (name + ': Pre link ');
},
Post:function (Scope, Ielem, iattrs) {
Console.log (name + ': Post link ');
}
}
}
}
}
}

App.directive (' Levelone ', createdirective (' Levelone '));
App.directive (' Leveltwo ', createdirective (' leveltwo '));
App.directive (' Levelthree ', createdirective (' Levelthree '));

The result is very simple: let ng handle three nested instructions, and each instruction has its own complile,pre-link,post-link function, each of which prints a line of things in the console to identify itself.

This example gives us a simple idea of the internal flow of NG while processing instructions.

Code output

The following is a result of the output from the console

If you want to try this example yourself, click this plnkr and then view the results in the console.

Analyze code

The first one to note is the order in which these functions are called:

Copy CodeThe code is as follows:
COMPILE PHASE
Levelone:compile function is called
Leveltwo:compile function is called
Levelthree:compile function is called

Pre-Link PHASE
Levelone:pre link function is called
Leveltwo:pre link function is called
Levelthree:pre link function is called

Post-link PHASE (Notice the reverse order)
Levelthree:post link function is called
Leveltwo:post link function is called
Levelone:post link function is called

This example clearly shows that NG compiles all the instructions before link, and then the link is divided into the pre-link and Post-link phases.

Note that the order of execution of compile and pre-link is executed sequentially, but Post-link is the opposite.

So the above has clearly identified the different stages, but what is the difference between compile and pre-link, is the same execution order, why is it divided into two different functions?

Dom

To dig deeper, let's simply modify the code above, and it will print the element variable in the parameter list in each function.

Copy CodeThe code is as follows:
var app = Angular.module (' Plunker ', []);

function createdirective (name) {
return function () {
return {
Restrict: ' E ',
Compile:function (TElem, tattrs) {
Console.log (name + ': Compile = + ' + telem.html ());
return {
Pre:function (Scope, Ielem, iattrs) {
Console.log (name + ': Pre link = + ' + ielem.html ());
},
Post:function (Scope, Ielem, iattrs) {
Console.log (name + ': Post link = + ' + ielem.html ());
}
}
}
}
}
}

App.directive (' Levelone ', createdirective (' Levelone '));
App.directive (' Leveltwo ', createdirective (' leveltwo '));
App.directive (' Levelthree ', createdirective (' Levelthree '));

Note that the output in the Console.log, except that the original HTML tag is not changed basically.

This should be able to deepen our understanding of these function contexts.

Run the code again to see

Output

The following is a result of the output from the console

If you want to run the results yourself, you can click on this plnkr and check the output in the console.

Observation

The results of the output DOM can expose some interesting things: DOM content is different in compile and pre-link two functions

So what's going on?

Compile

We already know that when Ng discovers that the DOM build is complete, it begins to process the DOM.

So when Ng walks through the DOM, it encounters the level-one element, which is understood from its definition to perform some necessary functions

Because the compile function is defined in the instruction object of the Level-one directive, it is called and passed an element object as its argument

If you look closely, you'll see that when the browser creates the element object, it's still the most primitive HTML tag

1. In Ng, the original DOM is often used to identify the template element, so I used the Telem name when defining the compile function parameter, which points to the template element.

Once you run the compile function in the Levelone directive, NG recursively iterates through its DOM nodes, and then repeats these operations on Level-two and Level-three.

Post-link

Before delving into the Pre-Link function, let's take a look at the Post-link function.

2. If you only use a link function when defining an instruction, NG will treat the function as a post-link, so we'll discuss the function first.
When Ng has traversed all the DOM and run through all the compile functions, the associated post-link function is called backwards.

The DOM now starts to reverse and executes the Post-link function, so the previous reverse call looks a bit strange, in fact it makes sense.

When running instruction Post-link that contains sub-directives, the reverse Post-link rule guarantees that the post-link of its sub-directives are already running.

So, when we run the Post-link function of the level-one instruction, we can guarantee that the post-link of Level-two and Level-three are actually running.

That's why people think Post-link is the safest or default place to write business logic.

But why is this element different from the compile?

Once NG invokes the compile function of the instruction, it creates an element instance object of the template element and provides it with a scope object, which may be a new instance, or it may already exist, possibly a child scope, It is also possible to have a separate scope, which depends on the scope attribute value in the directive definition object

So when linking occurs, this instance element and the scope object are already available, and are passed to the parameter list of the Post-link function as a parameter by NG.

1. I personally always use the Ielem name to define the parameters of a link function, and it is a pointer to the element instance

So the element parameter object of the Post-link (pre-link) function is an element instance rather than a template element.

So the output in the above example is different.

Pre-Link

When you write a post-link function, you can guarantee that the Post-link function of all its child directives is executed when the Post-link function is executed.

In most cases, it can be done better, so usually we will use it to write instruction code.

However, NG provides us with an additional hook mechanism, which is the Pre-Link function, which guarantees that the Post-link function of all child instructions is executed. Run some other code.

This sentence is worth repeated deliberation.

The Pre-Link function is guaranteed to execute before the post-link of the element instance and all of its child instructions are run.

So it makes the Post-link function reverse execute is quite meaningful, it itself is the original order of execution Pre-Link function

This also means that the Pre-Link function runs before the Pre-Link function of all its child instructions, so the complete reason is:

The Pre-Link function of an element is guaranteed to be executed before the Post-link and Pre-Link run on all of its child instructions. See:

Review

If we look back at the original output, we can clearly identify what happened:

Copy CodeThe code is as follows:
Here the ELEMENTS is still the ORIGINAL TEMPLATE ELEMENTS

COMPILE PHASE
Levelone:compile function is called on original DOM
Leveltwo:compile function is called on original DOM
Levelthree:compile function is called on original DOM

As of here, the ELEMENTS has BEEN instantiated and
is BOUND to A SCOPE
(e.g. Ng-repeat would have multiple INSTANCES)

Pre-Link PHASE
Levelone:pre link function is called on element instance
Leveltwo:pre link function is called on element instance
Levelthree:pre link function is called on element instance

Post-link PHASE (Notice the reverse order)
Levelthree:post link function is called on element instance
Leveltwo:post link function is called on element instance
Levelone:post link function is called on element instance

Profile

Looking back at the above analysis, we can describe the differences and usage of these functions:

Compile function

Use the compile function to change the production of the original Dom (template element) before NG creates the original Dom instance and creates the scope instance.

can be applied to situations where multiple element instances need to be generated, only one template element , Ng-repeat is the best example, it is in the compile function phase to change the original DOM to generate multiple original DOM nodes, Each then generates an element instance. Because compile only runs once, you can improve performance when you need to generate multiple element instances.

The template element and its associated attributes are passed as arguments to the compile function, but the scope is not available at this time:

Here's what the function looks like:

Copy CodeThe code is as follows:
/**
* Compile function
*
* @param telem-template Element
* @param tattrs-attributes of the template element
*/
function (TElem, tattrs) {

// ...

};

Pre-Link function

Use the Pre-Link function to run some business code after NG executes the compile function, but before the Post-link function of all its child instructions will be executed.

The scope object and the element instance will be passed as arguments to the Pre-Link function:

Here's what the function looks like:

Copy CodeThe code is as follows:
/**
* Pre-Link function
*
* @param scope-scope associated with this istance
* @param ielem-instance Element
* @param iattrs-attributes of the instance element
*/
function (scope, Ielem, iattrs) {

// ...

};

Post-link function

Use the Post-link function to execute the business logic, at which point it already knows that all of its child instructions have been compiled and the pre-link and Post-link functions have been completed.

This is why it is considered the safest and the default code for writing business logic.

The scope instance and the element instance are passed as arguments to the Post-link function:

Here's what the function looks like:

Copy CodeThe code is as follows:
/**
* Post-link function
*
* @param scope-scope associated with this istance
* @param ielem-instance Element
* @param iattrs-attributes of the instance element
*/
function (scope, Ielem, iattrs) {

// ...

};

Reference: http://www.jb51.net/article/58229.htm

The compile and link functions in ANGULARJS directives complement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.