为什么会发生这种无限$digest循环错误



我无法弄清楚为什么在这个简单的演示中出现无限$digest循环错误。我已经在官方文档中阅读了这些循环,但我不明白为什么这个演示会触发错误。

代码笔演示

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
    var TestApp = angular.module("TestApp", []);
    TestApp.controller("TestCtrl", function ($scope) {
      $scope.Counter = 0;
      $scope.IncrementCounter = function () {
        $scope.Counter+=1;
        return true
      }
    });
</script>
<body ng-app='TestApp'>
  <div ng-controller='TestCtrl'>
    <label>
      Number of times <code>$scope.IncrementCounter()</code>
      has been invoked: {{ Counter }}
    </label>
    <input type="hidden" value="{{ IncrementCounter() === true }}" />
  </div>
</body>

有没有办法在不导致整个模型经历摘要周期的情况下从$scope函数中增加$scope变量?

问题是因为您是从视图中的绑定中调用 IncrementCounter() 函数的。在一个$digest周期中,Angular 查看{{ }}括号并执行其中保存的任何函数,您的IncrementCounter()函数碰巧更改了作用域$scope.Counter上的值,这反过来又启动了另一个$digest循环,因此该过程不断重复。

您应该在控制器中执行所有这些操作,并且仅使用视图来显示作用域上的值。例如,您可以使用调用自身的函数来执行此操作,可以选择使用 $timeout 服务来创建延迟:

var TestApp = angular.module("TestApp", []);
TestApp.controller("TestCtrl", function ($scope, $timeout) {
  var init = function() {
    $scope.counter = 0;
    incrementCounter();
  };
  var incrementCounter = function () {
      $scope.counter++;
      $timeout(function() {
          incrementCounter();
      }, 1000);
  };
  init();
});

使用上面的代码,您的视图可以是:

<html>
  <head>
    <title>AngularJS Function Invocation Tester</title>
  </head>
    <body ng-app='TestApp'>
      <h2>AngularJS Function Invocation Tester</h2>
      <div ng-controller='TestCtrl'>
        <label>
          Number of times <code>$scope.IncrementCounter()</code>
          has been invoked: <span class="counter">{{ counter }}</span>
        </label>
      </div>
    </body>
</html>

最新更新