gpt4 book ai didi

javascript - $digest 在 $watch 定义触发 "$apply already in progress..."错误后不久

转载 作者:行者123 更新时间:2023-11-30 12:03:47 24 4
gpt4 key购买 nike

我是一个 Angular 菜鸟,我试图理解为什么以下会触发“$apply is already in progress ...”错误。

这是代码(几乎直接来自文档:https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest)

<!DOCTYPE html>
<html>

<head>
<script src="js/lib/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('MainController', ['$scope', function(scope) {
scope.name = 'misko';
scope.counter = 0;
//A
scope.$watch('name', function(newValue, oldValue) {
scope.count++;
});
//B
scope.$digest();
}]);
</script>
</head>

<body>
<div ng-app='app' ng-controller="MainController">
</div>
</body>

</html>

而且,这是 fiddle :https://jsfiddle.net/zLny2faq/5/

我收到臭名昭著的“$apply already in progress”错误,但这是为什么呢?

我想知道为什么摘要循环甚至没有被调用就触发了?

换句话说,我只是声明监视监听器 (@comment A) 并通过调用 $digest() (@comment B) 来触发它们。但是当我明确调用 $digest() 时,它似乎以某种方式被更快地调用并且出错了。为什么会这样?

请指教。

最佳答案

name 变量是在 watch 之前设置的,但是所有 watch 在初始化时都会被调用一次:

Per Angular Docs

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.

^ 可以照顾via :

$scope.$watch('name', function(newValue, oldValue) {
if (newValue !== oldValue) {
// will only run if the value changes, on initial load the newvalue = oldvalue so it won't run this code.
}
});

关于javascript - $digest 在 $watch 定义触发 "$apply already in progress..."错误后不久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35900079/

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