AngularJS中具有时间延迟的循环函数

时间:2014-03-11 16:18:02

标签: angularjs loops

所以我在AngularJS中创建一个简单的倒计时功能,这意味着倒数到输入中设置的时间。问题是我无法循环$scope.countdown函数。所以它只倒计时一次(如果我把$timeout($scope.countdown(), 1000);放进去 - 它完全断开了。)我只想让它每秒循环直到它达到0。

这是我的控制器:

function countdownController($scope) {

  $scope.hours = 2;
  $scope.minutes = 30;

  $scope.countdown = function(){
    if($scope.minutes == 0 && $scope.hours == 0){
        alert('end!');
        return;
    }
    else{
        if($scope.minutes == 0){
            $scope.minutes = 59;
            $scope.hours--;
        }
        else{
            $scope.minutes--;
        }

    }
    $timeout($scope.countdown(), 1000); //if I remove this - the numbers display - this actually breaks that.
  }

  $scope.countdown();
}

2 个答案:

答案 0 :(得分:3)

您正在寻找的是arguments.callee

$scope.countdown = function(){
    if($scope.minutes == 0 && $scope.hours == 0){
        alert('end!');
        return;
    }
    else{
        if($scope.minutes == 0){
            $scope.minutes = 59;
            $scope.hours--;
        }
        else{
            $scope.minutes--;
        }

    }
    $timeout(arguments.callee, 1000);
}

或者更多建议alternative

function countdownController($scope, $timeout) {
    $scope.hours = 0;
    $scope.minutes = 45;
    $scope.countdown = function myhandler() {
        console.log('call');
        if ($scope.minutes == 0 && $scope.hours == 0) {
            console.log('end!');
            return;
        } else {
            if ($scope.minutes == 0) {
                $scope.minutes = 59;
                $scope.hours--;
            } else {
                $scope.minutes--;
            }

        }
        $timeout(myhandler, 1000);
    }
}

JsFiddle Example

注意:如评论中所提到的,请勿忘记将$timeout注入您的控制器。

答案 1 :(得分:0)

您必须将函数传递给$ timeout服务。不是功能的结果。 试试这个:

$timeout($scope.countdown, 1000);