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

标签 javascript jquery angularjs

我是一个 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/

相关文章:

javascript - 如何检查所选文本是否可编辑?

javascript - 如何获取 jQuery 对象数组中选项的 value()

javascript - 确保在 UI 中对监视属性的更改生效后*执行代码

javascript - 在foreach函数之外访问$scope Angular js Firebase

javascript - 获得偏移然后使位置绝对

javascript - JavaScript 中的继承

javascript - 如何通过 NodeJS 发送带有 cookie 的 HTTP 请求?

javascript - 使用 jquery/d3 动态重用模板

javascript - 如何再次显示之前被 jQuery 隐藏的所有列表项?

javascript - Angular 1.4 - 获取父 Controller 属性