gpt4 book ai didi

angularjs - $watch 等待时间太长无法识别变化

转载 作者:行者123 更新时间:2023-12-03 08:21:43 25 4
gpt4 key购买 nike

这是 Controller 中的一些逻辑:

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。但是,watch 在那 3 秒内什么都不做,而是在 scope.gameOver 已经变回 false 的那 3 秒结束时触发。

这样做的正确方法是什么?

最佳答案

$watch 被设置时,你的 $watch 回调函数将至少被调用一次,不管你的 scope.gameOver 变量更改。

这在 official documentation 中指出:

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher.

我认为您可能会遇到意想不到的行为,因为您正在为 $watch 指定一个原始值,而不是对保存感兴趣值的变量的引用。

换句话说,

scope.$watch(scope.gameOver, function() { ... });

如您所指定,将与,

scope.$watch(true, function() { ... });

这显然不会做任何有成效的事情。

相反,更喜欢使用函数指定您的 $watch 以返回对 scope.gameOver 的引用,或者利用变量如何返回 $watch 可以是 Angular 表达式:

// 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() { ... });

希望对您有所帮助。

关于angularjs - $watch 等待时间太长无法识别变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420416/

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