Вопрос

I'm learning AngularJs but I cant make it works. I read about the digest cycle but it is not clear for me. It's obvious that this code fails because enter in a infinite loop, but I dont know how to fix it. Could someone help me?

<!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>

Thanks in advice!!!

Это было полезно?

Решение

Angular registers an implicit $watch on the home.getTitle() expression. This expression will get called at least twice because angular wants to check if the model has stabilized.

Your code returns a different string everytime home.getTitle() is called so angular continues digesting until it reaches the max digest cycles limit.

Try:

$scope.homeTitle = homeModel.getTitle();

and

<h3>{{homeTitle}}</h3>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top