问题
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);
}
});
In my view I simply have:
<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>
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.
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.
EDIT: 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.
回答1:
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();
});
}
or use a angular aware function such as $timeout. Check @asgoth answer in this question to create an angular aware setInterval() function.
回答2:
You can also use $scope.$digest() after you change model , but I think $scope.$apply is better
来源:https://stackoverflow.com/questions/17848063/angularjs-notifying-view-of-changes-to-model