angularJS中的超时功能

时间:2014-09-18 07:56:09

标签: javascript angularjs timer

我正在尝试在angularJS中实现一个简单的计时器。但是超时功能不起作用,尽管每个人都建议。

<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-sanitize.min.js"></script>

</head>
<body>

<div ng-app="ss" ng-controller="mainCtrl">
{{timeInMs}}
</div>

<script>
var myApp = angular.module("ss", ['ngSanitize']);
myApp.controller('mainCtrl', function ($sce, $scope) {

    $scope.timeInMs = 10;

        var countUp = function() {
            $scope.timeInMs+= 500;
            $timeout(countUp, 500);
        }

       $timeout(countUp, 500);


});

</script>

</body>
</html>

当我评论&#34; $ timeout(countUp,500);&#34;行,代码工作没有错误,但计时器不起作用。我是否需要包含更多javascript文件?

提前致谢。

1 个答案:

答案 0 :(得分:2)

您必须将$timeout服务注入控制器

var myApp = angular.module("ss", []);
myApp.controller('mainCtrl', function ($sce, $scope, $timeout) {

    $scope.timeInMs = 10;

    var countUp = function () {
        $scope.timeInMs += 500;
        $timeout(countUp, 500);
    }
    $timeout(countUp, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ss" ng-controller="mainCtrl">
    {{timeInMs}}
</div>