>我有以下代码
提琴手链接
目录:
<div ng-app ng-controller="ParentCtrl" ng-init="cities='North America'">
<div ng-controller="ChildCtrl as vm">
{{$parent.cities}}
<div>
<button ng-click="check()">Check the value</button>
</div>
</div>
</div>
Javascript:
function ParentCtrl($scope, $rootScope) {
$rootScope.$watch('changecity', function() {
$scope.cities = "South America";
console.log("changed the city");
});
$scope.cities = "North America";
}
function ChildCtrl($scope, $rootScope) {
$scope.check = function(){
console.log("$parent value:"+$scope.$parent.cities + "n$scope value:"+$scope.cities)
};
}
我有ng-init = "cities='North America'"
,也$scope.cities = "North America";
ParentCtrl
.
但是输出处的视图更新为南美洲,这很奇怪。有人可以解释上面代码块中发生的整个执行基础吗?
$watch
回调最初会执行吗?- 作用域覆盖的优先级是什么,即:监视回调中的范围覆盖先前设置的值?
$watch
在变量undefined
时开始监视。 $watch将在初始化时触发,因为它undefined
视为作用域变量中的新状态更改。除此之外,范围变量$scope.cities = 'North America'
的设置被视为变量的变化。这个变化触发了$watch
,而又会改变$scope.cities='South America'
。
要解决此问题,只需检查旧值是否未undefined
:
$rootScope.$watch('changecity', function(newvalue, oldvalue) {
// This will only change the cities if the original value was falsy
if(oldvalue) {
$scope.cities = "South America";
console.log("changed the city");
}
});
有关参考,请参阅:http://jsfiddle.net/7wr6ow57/4/