我有以下代码
Fiddler Link
HTML
<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
回调?答案 0 :(得分:2)
$watch
开始观察变量是undefined
的时间。 $ watch将在初始化时触发,因为它将undefined
视为scope-variable中的新状态更改。除此之外,范围变量$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");
}
});
:
WHERE date_col BETWEEN '01-JAN-1990' AND '01-JAN-2000'