This article mainly introduces the relevant information about the correct posture of Angularjs global variables being monitored by Scope. if you want to know the conclusion, you can refer to the following:
$scope.$watch($rootScope.xxx,function(newVal,oldVal){//do something})
Someone immediately asked why not:
$rootScope.$watch("xxx",function(newVal,oldVal){//do something})
From a recent bug, I explained why the first method is used.
Logic. At first I used $ rootScope. $ watch. Because angularjs watch on $ rootScope is valid globally once registered. My global variable happens to be the order information. that is to say, different controllers have changes to it. every change triggers $ rootScope. $ watch to enter another controller. Let's look at $ broadcast on $ rootScope.
In fact, this is not the only method. it is not difficult to find the watch method source code without the following code:
return function deregisterWatch() {if (arrayRemove(array, watcher) >= 0) {incrementWatchersCount(scope, -1);}lastDirtyWatch = null;};
This code tells us that manual cleaning of watch is feasible. For example:
Var watcher = $ rootScope. $ watch ("xxx", function () {}); // manually clear watcher ();
It's easy, right? the above method can also be used for the watch on the scope.
When I found this, I felt a problem. Will I be cleaned up in $ scope? As a result, call and continue to the source code. I found the following code in the $ destroy method:
// Disable listeners, watchers and apply/digest methodsthis.$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 the correct posture for Angularjs global variables to be listened to by Scope. I hope you can help. if this article is not well written, please kindly advise.