2014-05-15 86 views
0

我正在學習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> 

謝謝你的建議!!!

回答

5

Angular在home.getTitle()表達式上註冊了隱式$ watch。這個表達式至少會被調用兩次,因爲角度想要檢查模型是否穩定。

您的代碼每次都會返回一個不同的字符串home.getTitle()被調用,因此角度會持續消化,直至達到最大摘要週期限制。

嘗試:

$scope.homeTitle = homeModel.getTitle(); 

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