AngularJS $ watch不等待触发器发生,在回调函数内执行$ scope

时间:2016-01-15 16:18:32

标签: javascript angularjs angularjs-scope

我有以下代码

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

但输出视图更新为南美,这很奇怪。有人可以解释上面代码块中发生的整个执行基础。

  1. 最初是否执行$watch回调?
  2. 范围覆盖的优先级是什么,即:监视回调中的范围是否覆盖先前设置的值?

1 个答案:

答案 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'

参考:http://jsfiddle.net/7wr6ow57/4/