AngularJS通知模型更改视图 [英] AngularJS notifying view of changes to model
问题描述
我试图在基于控制器中Javascript Date对象的视图中显示当前时间.我的控制器如下所示:
I'm trying to display the current time in a view based on a Javascript Date object in my controller. My controller looks like this:
myApp.controller('DateCtrl', function($scope) {
var date = new Date();
$scope.minutes = date.getMinutes();
$scope.hours = date.getHours();
$scope.seconds = date.getSeconds();
var updateTime = function() {
var date2 = new Date();
$scope.minutes = date2.getMinutes();
$scope.hours = date2.getHours();
$scope.seconds = date2.getSeconds();
}
$scope.clickUpdate = function() {
setInterval(updateTime, 1000);
}
});
我认为我只有:
<div ng-controller="DateCtrl">
<div>This is the hour: {{ hours }}</div>
<div>This is the minute: {{ minutes }}</div>
<div>This is the second: {{ seconds }}</div>
<button ng-click="clickUpdate()">Click Update Here!</button>
</div>
由于某种原因,setInterval()
方法仅工作一次,而我无法使其按设置每1秒钟继续运行updateTime()
.我输入了一个简单的console.log()
语句,该语句每1秒运行一次...所以我很困惑.
For some reason, the setInterval()
method works only once and I can't get it to keep running updateTime()
every 1 second as was set. I put in a simple console.log()
statement and that ran every 1 second...so I'm very confused.
我还检查了$scope.watch()
和$scope.digest()
,但是我不确定如何使用它们/如果在这种情况下应该使用它们.
I've also checked out $scope.watch()
and $scope.digest()
but I'm not quite sure how they can be used/if I'm supposed to use them in this scenario.
进一步检查后,似乎setInterval
工作正常,每1秒调用一次updateTime()
,但是每次调用后范围内的值都不会反映在我的视图中.
Upon further inspection, it appears as if the setInterval
is working properly, calling updateTime()
every 1 second, but the values in the scope aren't being reflected in my view after every call.
推荐答案
这是因为您正在将范围从更改到角度世界之外(setInterval).您必须$apply
更改:
It's because you are changing the scope from outside the angular world (setInterval). You must $apply
the changes:
var updateTime = function() {
$scope.$apply(function(){
var date2 = new Date();
$scope.minutes = date2.getMinutes();
$scope.hours = date2.getHours();
$scope.seconds = date2.getSeconds();
});
}
或使用可识别角度的函数,例如$timeout
.在此问题中检查@asgoth答案以创建可识别角度的 > setInterval()
函数.
or use a angular aware function such as $timeout
. Check @asgoth answer in this question to create an angular aware setInterval()
function.
这篇关于AngularJS通知模型更改视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!