gpt4 book ai didi

javascript - AngularJS $watch 不等待触发发生,执行回调函数内的 $scope

转载 作者:行者123 更新时间:2023-12-02 15:10:38 25 4
gpt4 key购买 nike

我有以下代码

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 .

但是输出的 View 被更新为南美洲,这很奇怪。有人可以解释一下上面代码块中发生的整个执行原理吗?

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

最佳答案

$watch 当变量未定义时开始监视。 $watch 将在初始化时触发,因为它将 undefined 视为作用域变量中的新状态更改。除此之外,范围变量 $scope.cities = 'North America' 的设置被视为变量的更改。此更改会触发 $watch,后者又会更改 $scope.cities='South America'

要解决此问题,只需检查旧值是否未定义:

$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/

关于javascript - AngularJS $watch 不等待触发发生,执行回调函数内的 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com