本文介绍了angularJS 中的超时功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 angularJS 中实现一个简单的计时器.但是超时功能虽然大家都建议了,但还是不行.

<html lang="zh-cn"><头><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><身体><div ng-app="ss" ng-controller="mainCtrl">{{timeInMs}}

<脚本>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);});</html>

当我注释掉$timeout(countUp, 500);"时行,代码正常工作,但计时器不起作用.我需要包含更多的 javascript 文件吗?

提前致谢.

解决方案

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

var myApp = angular.module("ss", []);myApp.controller('mainCtrl', function ($sce, $scope, $timeout) {$scope.timeInMs = 10;var countUp = 函数 () {$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}}

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.

解决方案

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>

这篇关于angularJS 中的超时功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 07:04