$ Apply () in angularJS _ AngularJS-js tutorial

Source: Internet
Author: User
This article mainly introduces the $ apply () method in angularJS. For more information, see Javascript, to get started with angular JS directly, there are still a lot of obstacles. However, I believe that even anti-human design is not a big problem.

Okay. To understand what angular JS is, I start with Scope. So what is Scope? Borrow a paragraph from the official document:

The Code is as follows:


"Scope is an object that refers to the application model. it is an execution context for expressions. scopes are arranged in hierarchical structure which mimic the DOM structure of the application. scopes can watch expressions and propagate events."

After reading this, similar to other programming languages, the Scope is like the Scope of the Data Model. It provides context for the execution of the Expressions.

Features of Scope

Next, let's take a look at the features of Scope?

Scope provides the $ watch method to monitor Model changes.
Scope provides the $ apply method to spread Model changes.
Scope can be inherited to isolate different application components and attribute access permissions.
Scope provides context for Expressions computing.

For these four features, because I have studied ActionScript, C ++, and Java before, it is difficult to understand the first, third, and fourth points, but the second point is a bit confused. Based on the principle of breaking the sandpot question, I found something through Google. For experienced veterans, please pat the bricks!

Source Javascript

First of all, scope. apply () seems to be an ordinary method to update bindings. But think a little more, why do we need it? When should I use it? To understand these two problems, we have to start with Javascript. In Javascript code, all are executed in a certain order. When it is the turn to execute a code snippet, the browser will only execute the current snippet without doing anything else. So sometimes some poor web pages will get stuck when you click something, and Javascript's way of working is one of the reasons for this phenomenon! Let's take a look at the following code:

The Code is as follows:


Var button = document. getElementById ('clickme ');
Function buttonClicked (){
Alert ('the button was clicked ');
}
Button. addEventListener ('click', buttonClicked );
Function timerComplete (){
Alert ('timer complete ');
}
SetTimeout (timerComplete, 5000 );

When loading Javascript code, first find a button with the id "clickMe", add a listener, and set timeout. Wait for 5 seconds. A dialog box is displayed. If you refresh the page and click the clickMe button immediately, a dialog box will pop up. If you do not click OK, The timerComplete function will never be executed.

How to update bindings

Well, after pulling something seemingly unrelated, let's get back to the question. How does angular JS know when data changes and pages need to be updated? The code needs to know when the data has been modified, but there is no way to directly notice that the data on an object has changed (although ECMAScript 5 is trying to solve this problem, but it is still in the experimental stage ). Currently, there are two mainstream strategies. One is to use a special object so that all data can be set only by calling the method of the object, rather than directly using the property. In this way, all the modifications can be recorded and the page needs to be updated. The disadvantage of doing so is that we must inherit a special object. You can assign values only through object. set ('key', 'value') instead of object. key = value. In the Framework, like EmberJS and KnockoutJS do this (although I have never touched the -- keystore ). The other method is angular JS. After each Javascript code execution sequence is executed, it checks whether there is any data change. This does not seem efficient, or even seriously affects performance. However, angular JS uses some clever methods to solve this problem (it has not been studied yet and is not clear yet ). The advantage of doing so is that we can use any object at will, there is no restriction on the Assignment Method, and we can also perceive the changes to data.
For this solution adopted by angular JS, we are concerned about when the data has changed, and this is exactly where scope. apply () comes in handy. Check whether the bound data has changed. It is actually caused by scope. digest () is complete, but we almost never directly call this method, but call scope. apply () method, because in scope. in the apply () method, it will call scope. digest () method. The scope. apply () method carries a function or expression, executes it, and finally calls the scope. digest () method to update bindings or watchers.

When to use $ apply ()

Or that question, when do we need to call the apply () method? In fact, almost all of our code is packaged in scope. apply (), such as ng-click, controller initialization, and http callback functions. In these cases, we do not need to call it by ourselves. In fact, we cannot call it by ourselves. Otherwise, an error will be thrown when we call the apply () method in the apply () method. If we need to run code in a new execution sequence, and this new execution sequence is not created by the method of angular JS library, in this case, we need to use scope. apply. The following is an example:

The Code is as follows:


{Message }}


The Code is as follows:


FunctionCtrl ($ scope ){
$ Scope. message = "Waiting 2000 ms for update ";
SetTimeout (function (){
$ Scope. message = "Timeout called! ";
// AngularJS unaware of update to $ scope
},2000 );
}

After the above code is executed, the page displays: Waiting 2000 ms for update. Obviously, data updates are not noticed by angular JS.
Next, we will slightly modify the Javascript code and pack it with scope. apply.

The Code is as follows:


FunctionCtrl ($ scope ){
$ Scope. message = "Waiting 2000 ms for update ";
SetTimeout (function (){
$ Scope. $ apply (function (){
$ Scope. message = "Timeout called! ";
});
},2000 );
}

This time, unlike the previous one, the page will first display: Waiting 2000 ms for update. After 2 seconds, the content will be changed to: Timeout called! . Obviously, angular JS is aware of data updates.
NOTE: we should not do this, but use the timeout method provided by angular JS, so that it will be automatically wrapped with the apply method.

Science is a double-edged sword
Finally, let's take a look at the scope. apply () and scope. apply (function) methods! Although angular JS has done a lot for us, we have lost some opportunities. You can see from the pseudocode below:

The Code is as follows:


Function $ apply (expr ){
Try {
Return $ eval (expr );
} Catch (e ){
$ ExceptionHandler (e );
} Finally {
$ Root. $ digest ();
}
}

It will capture all exceptions and will not throw them out. It will call the $ digest () method.

To sum up

The $ apply () method can execute angular JS expressions outside the angular framework, such as DOM events, setTimeout, XHR, or other third-party libraries. This is just the beginning, and the water is still very deep. Welcome to deep pe!

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.