我想在 AngularJS 中使用 javascript setTimeout,该计数值每秒都会增加:
<!DOCTYPE html>
<html>
<head>
<title>MyCount</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript">
如何正确书写
function myController($scope) {
$scope.count = 1;
$scope.delayInc = function () {
$timeout(function () {
$scope.count += 1;
}, 1000);
};
}
</script>
计数不停留在 1 ?
<h2>My Second Count: {{count}}</h2>
</body>
</html>
谢谢
更相关:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
{{iterator}}
</body>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', '$interval', function($scope, $interval) {
$scope.iterator = 1;
var interval = $interval(function() {
$scope.iterator++;
if ($scope.iterator > 10) {
$interval.cancel(interval);
}
}, 1000);
}]);
</script>
</html>
你的代码有几个问题。首先,您正在定义 delayInc() 函数,但您从未调用它。因此,从未安排过任何$timeout。这需要在控制器中调用,或者您需要从某个事件(例如在按钮上单击)启动它。
其次,从您的描述来看,听起来您希望它每秒增加一次。使用 $timeout 只会递增一次 - 调用 delayInc() 后一秒。
看看下面的方法,显示$timeout工作以及使用$interval每秒进行一次:
<body ng-controller="MainCtrl">
<p>Count (timeout): {{count}}!</p>
<button ng-click="delayInc()">Start Delay Timer</button>
<p></p>
<p>Count2 (interval): {{count2}}!</p>
<button ng-click="repeatInc()">Start Interval Counter</button>
</body>
app.controller('MainCtrl', function($scope, $timeout, $interval) {
$scope.count = 1;
$scope.count2 = 1;
$scope.delayInc = function() {
$timeout(function() {
$scope.count += 1;
}, 1000);
};
$scope.repeatInc = function() {
$interval(function() {
$scope.count2 += 1;
}, 1000);
}
这是所有工作的 Plunker:http://plnkr.co/edit/c0EFB7Lbs6ZjJL5NQf86?p=preview