Angularjs $watch等待时间过长,无法识别变化
这是控制器中的一些逻辑:Angularjs $watch等待时间过长,无法识别变化,angularjs,Angularjs,这是控制器中的一些逻辑: function newGame(){ $scope.gameOver = true; $timeout(function(){ //do stuff $scope.gameOver = false; }, 3000); } 在一项指令中,我有: scope.$watch(scope.gameOver,function(){ console.log("changed!", scope.gameO
function newGame(){
$scope.gameOver = true;
$timeout(function(){
//do stuff
$scope.gameOver = false;
}, 3000);
}
在一项指令中,我有:
scope.$watch(scope.gameOver,function(){ console.log("changed!", scope.gameOver);})
我想做一些基于scope.gameOver的事情。我使用超时功能给游戏3秒钟的时间,其中gameOver=true。然而,手表在这3秒钟内什么也不做,而是在scope.gameOver已经变回false的3秒钟结束时触发
正确的方法是什么?只有当Watch参数更改时,Watch才会被触发。因此,在您的代码中,$scope.gameOver
只有在3秒钟结束时才改变,因此手表被触发 设置
$watch
时,无论scope.gameOver
变量是否更改,您的$watch
回调函数将至少调用一次
报告指出了这一点:
在向作用域注册观察程序后,异步调用侦听器
fn(通过$evalAsync
)初始化观察程序
我认为您可能会遇到意外的行为,因为您正在向$watch
指定一个基本值,而不是对包含感兴趣值的变量的引用
换句话说,
scope.$watch(scope.gameOver, function() { ... });
如您所述,将与
scope.$watch(true, function() { ... });
这显然不会产生任何效果
相反,最好使用函数返回对scope.gameOver
的引用来指定$watch
,或者利用$watch
的变量可以是角度表达式的方式:
// Function to return reference to the variable to watch
scope.$watch(function() { return scope.gameOver; }, function() { ... });
// Expression for Angular to evaluate
scope.$watch('gameOver', function() { ... });
希望能有所帮助。它的价值与参考价值是一致的!谢谢