Javascript, AngularJS and setTimeout function
Javascript, AngularJS and setTimeout function
我想在 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>
谢谢
$interval与此
更相关:
<!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
相关文章:
- setInteval vs setTimeout
- 直接在函数声明上使用function.prototype.bind
- jQuery:.click(function(){(element),collapse('show',f
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- setTimeout可以与闭包内的函数一起使用吗
- Javascript setTimeout for an array
- 刷新后,setTimeout将工作或不工作
- 如果连接类型为none,则Javascript Function Only警报
- Javascript setTimeout function with JQuery
- 将 setTimeOut 添加到 Google Analytics Function
- Javascript, AngularJS and setTimeout function
- Javascript - setTimeout function
- setTimeout on Hover function
- Javascript setTimeout function with 'this'
- cordova setTimeout function
- Javascript setTimeout function
- 防止onclick-function在settimeout函数中被激活
- 字段焦点在firefox中不工作,setTimeout(function(){id.focus();},0);
- Nodejs setTimeOut function
- 在$后运行function.每个都在setTimeout()中