Angularjs $apply () method in detail

Source: Internet
Author: User

This article mainly introduces the Angularjs in the $apply () method in detail, the need for friends can refer to the following

For a in front of a pure novice I, JavaScript is still smattering, want to directly get started angular JS, encountered a lot of resistance. But I believe that as long as the effort, even anti-human design is not a big problem.

Okay, don't say much nonsense. To figure out what angular JS is, I started with scope. So what is scope? A passage that borrows official documents:

The code is as follows:
"Scope is a object that refers to the application model. It is a execution context for expressions. Scopes is arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events. "

After reading, analogy to other programming languages, the sense that scope is like the scope of the data model, for the execution of expressions to provide context, let's first understand it.

Features of scope

Next, look at what are the features of scope?

Scope provides the $watch method to monitor the model changes.
Scope provides the $apply method for propagating model changes.
Scope can be inherited to isolate different application components and attribute access rights.
Scope provides context for the calculation of expressions.

For this four-point feature, because I previously learned ActionScript, C + +, Java, so 第一、三、四点 is not difficult to understand, but the 2nd feeling a little foggy. In accordance with the principle of ask why, I still search through Google some things. For experienced veteran, please tap on the board!

SOURCE JavaScript

First of all, at first glance, scope.apply () seems to be an ordinary way to make bindings updated. But just a little bit more, why do we need it? When do you usually use it? To figure out these two questions, you have to start with JavaScript. In JavaScript code, it executes in a certain order, and when it's time to execute a code snippet, the browser simply executes the current fragment and does nothing else. So sometimes some of the web pages that are not very good, when clicked on something will be stuck, JavaScript work is the cause of this phenomenon is one of the reasons! Below we have a code to feel:

Copy CodeThe 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 an ID called "ClickMe" button, then add a listener, and then set the timeout. Wait 5 seconds and a dialog box will pop up. If you refresh the page and immediately click on the ClickMe button, a dialog will pop up and if you do not click the Ok,timercomplete function will never be able to execute.

How to update bindings

Well, after pulling some seemingly unrelated stuff, we get back to the point. Angular JS is how to know when the data changes and the page needs to be updated? The code needs to know when the data has been modified, but there is now no way to directly notify that the data on an object has changed (although ECMAScript 5 is trying to solve the problem, it is still in the experimental phase). At present, there are two solutions to the mainstream strategy. One is the need to use special objects, so that all data can only be set by invoking the object's method, rather than directly through the property designation. In this case, all the changes can be recorded and you will know when the page needs to be updated. The disadvantage of this is that we have to inherit a special object. The assignment can only be done by Object.set (' key ', ' value ') and not object.key=value. In the frame, like Emberjs and Knockoutjs, that's what it's all about (though I've never been in touch--embarrassing). The other is the way that angular JS is used, to check for changes in the data after each execution of the JavaScript code execution sequence. This does not seem to be efficient or even seriously impacting performance. But angular JS used some clever means to solve the problem (not yet studied, it is unclear). The advantage of this is that we can use arbitrary objects arbitrarily, there is no limit to the way of assignment, and can be aware of changes in the data.
For angular JS to take this solution, we are concerned about when the data has changed, and this is where scope.apply () come in handy. It is actually done by scope.digest () to check that the data of the binding has changed, but we almost never call this method directly, but instead call the Scope.apply () method, because in the Scope.apply () method, It will go to call the Scope.digest () method. The Scope.apply () method takes a function or an expression, executes it, and finally calls the Scope.digest () method to update bindings or watchers.

When to use $apply ()

Or that question, when exactly do we need to call the Apply () method? The situation is very small, in fact almost all of our code is wrapped in scope.apply (), like Ng?click,controller initialization, HTTP callback function, etc. In these cases, we do not need to call ourselves, in fact, we can not invoke, otherwise in the Apply () method calls the Apply () method will throw an error. We need to wrap the code in scope.apply () if we need to run the code in a new execution sequence, and we need to use it only when the new execution sequence is not created by the method of the angular JS library. Here is an example to explain:

Copy CodeThe code is as follows:
<div ng:app ng-controller= "Ctrl" >{{message}}</div>

Copy CodeThe code is as follows:
Functionctrl ($scope) {
$scope. Message = "Waiting 2000ms for Update";
SetTimeout (function () {
$scope. Message = "Timeout called!";
AngularJS unaware of update to $scope
}, 2000);
}

The above code executes after the page is displayed: Waiting 2000ms for update. Obviously the update of the data is not aware by angular JS.
Next, we change the JavaScript code slightly and wrap it up in scope.apply ().

Copy CodeThe code is as follows:
Functionctrl ($scope) {
$scope. Message = "Waiting 2000ms for Update";
SetTimeout (function () {
$scope. $apply (function () {
$scope. Message = "Timeout called!";
});
}, 2000);
}

This time, unlike before, the page will first show: Waiting 2000ms for update, wait 2 seconds after the content will be changed to: Timeout called!. Obviously the data update is angular JS aware of.
Note: We should not do this, but instead use the timeout method provided by angular JS, so that it will be automatically wrapped up 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 of things for us, we have lost some chances. From the pseudo-code below, you will know:


Function$apply (expr) {
try {
Return$eval (expr);
} catch (e) {
$exceptionHandler (e);
} finally {
$root. $digest ();
}
}

It will catch all exceptions and will not be thrown again, and will call the $digest () method at the end.

Summarize

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, the water is still very deep, welcome to come with us to deeply dive

Angularjs $apply () method in detail

Related Article

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.