Angularjs the correct posture of the global variable being monitored by the scope _angularjs

Source: Internet
Author: User

If you only want to know the conclusion:

$scope. $watch ($rootScope. Xxx,function (newval,oldval) {
//do something
})

Someone immediately asks why not:

$rootScope. $watch ("xxx", function (newval,oldval) {
//do something
})

From one of my recent bugs, why use the first method.

Logic as pictured, I used the $rootScope. $watch in the beginning. Because the Angularjs on the $rootScope watch once registered globally valid. And my global variable happens to be order information, which means that different controller have changes to him, and every change triggers $rootScope. $watch into other controller. You can take a look at the $broadcast on the $rootScope to go global.

In fact, this is not the only way to check the angular source code is not hard to find watch method source codes are as follows:

return function Deregisterwatch () {
if (Arrayremove (array, watcher) >= 0) {
incrementwatcherscount (scope,-1 );
}
Lastdirtywatch = null;

This code tells us that it is possible to manually clean the watch. For example:

var watcher = $rootScope. $watch ("xxx", function () {});
Manual removal of watcher 
watcher ();

Still very simple, right, the above method can also be used for scope of watch.

When studying here, I feel a little bit of a problem, so will I be cleaned up in $scope? So shout, continue to turn source, I found the following code in $destroy method:

Disable listeners, Watchers and Apply/digest methods this. $destroy = this. $digest = this. $apply = this.
$evalAsync = this. $applyAsync = NoOp;
this. $on = this. $watch = this. $watchGroup = function () {return 
noop; 
};
this.$ $listeners = {};

The above code is introduced in this article to the ANGULARJS global variable by the scope of the correct posture monitoring, I hope everyone has helped, this article is not good to write a lot of heroes please advice.

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.