我试图在我的 Controller 中基于 Javascript Date 对象的 View 中显示当前时间。我的 Controller 看起来像这样:
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 秒运行一次...所以我很困惑。
我还查看了 $scope.watch()
和 $scope.digest()
但我不太确定如何使用它们/如果我应该在这种情况下使用它们。
编辑:经进一步检查,似乎 setInterval
正常工作,每 1 秒调用一次 updateTime()
,但范围内的值每次通话后都不会反射(reflect)在我的 View 中。
最佳答案
这是因为您要从 Angular 世界之外 (setInterval) 更改范围。您必须$apply
更改:
var updateTime = function() {
$scope.$apply(function(){
var date2 = new Date();
$scope.minutes = date2.getMinutes();
$scope.hours = date2.getHours();
$scope.seconds = date2.getSeconds();
});
}
或使用 Angular 感知 函数,例如 $timeout
。在 this question 中查看 @asgoth 的回答创建一个 Angular 感知 setInterval()
函数。
关于javascript - AngularJS 通知模型更改的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848063/