$ scope函数未定义(匿名函数)

时间:2014-12-03 13:06:43

标签: angularjs angularjs-scope

我有这段代码:

  $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功能时,我收到错误:

  

未捕获的ReferenceError:未定义startTimer(匿名   功能)

我做错了什么?

1 个答案:

答案 0 :(得分:6)

而不是:

  setTimeout('startTimer()', 1000);

使用angularjs等效:

  $timeout($scope.startTimer, 1000);

编辑:正如切尔尼夫所建议的,将$timeout依赖关系注入您的控制器非常重要,因此如果您有一个名为myCtrl的控制器:

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