Understanding of $apply () in angular JS

Source: Internet
Author: User

Angular's most compelling feature is the two-way binding, but how it does it, I can summarize two points:

    • Transfer the changed data from model to view--> $apply

    • Transfer the changed data from view to Model--> $watch


This function is based on scope and propagates the state of the members of the scope object. So, I might as well start with scope. So what is scope? A passage that borrows official documents:

"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, feel that scope is like the scope of the data model, to provide context for the execution of expressions.

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.

SOURCE JavaScript

First of all, at first glance, $scope. $apply () seems to be an ordinary way to get 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:

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. That's because the changes to the membership have not been updated

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 uses some ingenious means to solve this problem ( later have the opportunity to study well ). 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 exactly what $scope. $apply () comes in handy. It is actually done by $scope $digest () to check that the data for the binding has changed, but we almost never call this method directly, but instead call $scope. $apply () method, because inside the $scope. $apply () method , it will go to call the $scope. $digest () method. $scope. The $apply () method takes a function or an expression, executes it, and finally calls the $scope. $digest () method to update the 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, virtually all of our code is wrapped in $scope. $apply () inside, like Ng-click,controller initialization, $http destroy function, etc. In these cases, we do not need to call ourselves, in fact, we can not call ourselves, otherwise the $apply () method inside the call $apply () method will throw an error. If we need to run the code in a new execution sequence then we really need to use it, and when this new execution sequence is not created by the method of the angular JS library, we need to wrap the code in $scope. $apply (). Here is an example to explain:

[HTML]

<div ng:app ng-controller= "Ctrl" >{{message}}</div>

[Javascript]

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'll change the JavaScript code slightly and wrap it up with $scope. $apply ().

[Javascript]

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 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 $scope. $apply () and $scope. $apply (function) Method! 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.


Understanding of $apply () in angular JS

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.