我正在尝试在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>
当我注释掉“ $ timeout(countUp,500);”时 行,代码可以正常工作,但计时器不起作用。我还需要添加其他JavaScript文件吗?
提前致谢。
您必须将$timeout服务注入控制器
$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>