Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

javascript - Timeout function in angularJS

I am trying to implement a simple timer in angularJS. But timeout function is not working though it is suggested by everyone.

<!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>

When I comment out the " $timeout(countUp, 500);" line, the code works without error but timer doesn't work. Do i need to include any more javascript file?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to inject the $timeout service to the controller

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...