window.setInterval 不适用于 angularjs [英] window.setInterval not working on angularjs
本文介绍了window.setInterval 不适用于 angularjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一小段使用 setInterval 方法的代码:
function MyController($scope) {$scope.clock = new Date();var updateClock = function() {$scope.clock = new Date();};设置间隔(更新时钟,1000);};
和html如下:
<头><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>头部><身体><div ng-controller="MyController"><h1>你好{{时钟}}!</h1>
<script type="text/javascript" src="script.js"></script></html>
然而,MyController
中的 setInterval
不会更新时间.这里可能哪里出错了?
根据一本书,它是这样工作的:
function MyController($scope) {$scope.clock = new Date();var updateClock = function() {$scope.clock = new Date();};设置间隔(函数(){$scope.$apply(updateClock);}, 1000);更新时钟();};
为什么不使用 @scope.$apply 会出现什么问题?
解决方案
使用 angular $interval 服务.
function($scope, $interval) {$scope.clock = new Date();var updateClock = function() {$scope.clock = new Date();};$interval(updateClock, 1000);}
I have this small piece of code that uses setInterval method:
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(updateClock, 1000);
};
and html as follows:
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
</head>
<body>
<div ng-controller="MyController">
<h1>Hello {{ clock }}!</h1>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
However, setInterval
in MyController
does not update time.
Where possibly is wrong here ?
It works this way according to a book :
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
};
Why is that and what goes wrong without using @scope.$apply ?
解决方案
Use the angular $interval service.
function($scope, $interval) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
$interval(updateClock, 1000);
}
这篇关于window.setInterval 不适用于 angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文