2014-12-03 41 views
0

我有這樣的代碼:

$scope.startTimer = function(){ 
    $scope.settings.showMinutes = false; 
    $scope.settings.showStart = false; 
    $scope.settings.showPause = true; 
    $scope.settings.showReset = true; 
    $scope.settings.showDonate = false; 
    if ($scope.settings.seconds <= 0) { 
     $scope.settings.seconds = 59; 
     $scope.settings.minutes -= 1; 
     if ($scope.settings.minutes < 0) { 
     $scope.settings.showPause = false; 
     $scope.settings.stopTimer = true; 
     return; 
     } 
     setTimeout('startTimer()', 1000); 
    } else { 
     $scope.settings.seconds -= 1; 
     setTimeout('startTimer()', 1000); 
    } 
    } 

當我開始startTimer功能我得到錯誤:

Uncaught ReferenceError: startTimer is not defined (anonymous function)

我在做什麼錯?

+0

我認爲你應該通過$ scope.startTimer作爲setTimeout的第一個參數。 – Rasalom 2014-12-03 13:08:07

+0

請避免將字符串文字傳遞給setTimeout。請參閱:https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout#Passing_string_literals 它們在全局範圍內調用,而不是在角度風格的$範圍內調用。 – CKK 2014-12-03 13:11:59

回答

6

相反的:

setTimeout('startTimer()', 1000); 

使用angularjs相當於:

$timeout($scope.startTimer, 1000); 

編輯:由於Cherniv建議,它注入$timeout依賴於你的控制器是很重要的,因此,如果您有一個名爲myCtrl的控制器:

angular.module("myApp").controller("myCtrl", ['$timeout', function($timeout){ 
    $scope.startTimer = function(){ 
     //Your code 
    } 
}]); 
+1

你應該提到'$超時'注射.. – Cherniv 2014-12-03 13:10:25

+1

嘿傢伙,它的工作就像一個魅力:)非常感謝你的幫助。 – bartoszstaryga 2014-12-03 13:20:58