infdig Infinite $ digest循环

时间:2014-05-15 17:12:15

标签: javascript angularjs angularjs-scope

我正在学习AngularJs,但我无法让它发挥作用。 我读到了摘要周期,但对我来说并不清楚。 显而易见,此代码失败是因为进入无限循环,但我不知道如何修复它。 有人能帮助我吗?

<!DOCTYPE html>
<html lang="eng" ng-app="test">
<head>
  <title>Learning Angular</title>
  <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js"></script>
  <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.js"></script>
  <script type="text/javascript">
    var app = angular.module('test', ['ngRoute']);

    app.factory('visitCounterService', function () {
      var counterService = function() {
        var _count = 1;

        var counter = function() { return _count++; };

        return { counter: counter }
      }();

      return counterService;
    });

    app.service('homeModel', ['visitCounterService', function(visitCounterService){
      this.getTitle = function() {
        var n = visitCounterService.counter();
        return "Welcome to this awesome demo. You are the visitor n° " + n;
      };

    }]);

    app.controller('homeController', ['$scope', 'homeModel', function($scope, homeModel) {
      $scope.home = homeModel;
    }]);
  </script>
</head>
<body ng-controller="homeController">
  <h3>{{home.getTitle()}}</h3>
</body>
</html>

感谢您的建议!!!

1 个答案:

答案 0 :(得分:5)

Angular在home.getTitle()表达式上注册隐式$ watch。此表达式将被调用至少两次,因为angular想要检查模型是否已稳定。

每次调用home.getTitle()时,您的代码都会返回一个不同的字符串,因此angular会继续消化,直到达到最大摘要周期限制。

尝试:

$scope.homeTitle = homeModel.getTitle();

<h3>{{homeTitle}}</h3>