本文介绍了angularJS中的超时功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在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>
当我注释掉$ timeout(countUp,500);行,代码工作没有错误但计时器不起作用。我是否需要包含更多javascript文件?
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?
提前致谢。
推荐答案
您必须将 $ timeout
服务注入控制器
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中的超时功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!