如果你只想知道結論:
$scope.$watch($rootScope.xxx,function(newVal,oldVal){//do something}) 馬上就有人問為什么不是:
$rootScope.$watch("xxx",function(newVal,oldVal){//do something}) 從我最近的一個bug來說說為什么要用第一種方式。
邏輯如圖,一開始我使用了 $rootScope.$watch 的寫法。因為 angularjs 在 $rootScope 上的 watch 一旦注冊全局有效。而我的這個全局變量恰好是訂單信息,也就是說不同的 controller 對他都是有改動的,每一次改動就會觸發 $rootScope.$watch 進入別的 controller。可以類比看一下 $rootScope 上的 $broadcast 會全局出發的。
其實這并不是唯一的方式,查一下angular 源碼不難找到 watch 方法源碼不分有如下代碼:
return function deregisterWatch() {if (arrayRemove(array, watcher) >= 0) {incrementWatchersCount(scope, -1);}lastDirtyWatch = null;}; 這段代碼告訴我們,手動清理 watch 是可行的。例如:
var watcher = $rootScope.$watch("xxx",function(){});//手動清除 watcher watcher(); 還是很簡單對吧,以上方法同樣可以用于 scope 上的 watch。
研究到這里的時候,覺得有點問題,那我在 $scope 會被清理么?于是呼,繼續翻源碼,我在 $destroy 方法里面找到如下代碼:
// 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 = {}; 以上代碼是本文給大家介紹的Angularjs全局變量被作用域監聽的正確姿勢,希望大家有所幫助,本文寫的不好還請各位大俠多多指教。



















