Reputation: 59
Why does digest loop not trigger for the following code, even though the now
variable is changed?
var app = angular.module('coolName',['ngResource']);
app.controller('TimeController', function($scope) {
$scope.now = new Date().toLocaleTimeString();
setInterval(function() {
$scope.now = new Date().toLocaleTimeString();
console.log($scope.now);
}, 1000);
});
Upvotes: 2
Views: 72
Reputation: 8971
Use $interval
instead of setInterval
:
app.controller('TimeController', function($scope, $interval) {
$interval(function() {
$scope.now = new Date().toLocaleTimeString();
console.log($scope.now);
}, 1000);
});
setInterval
is not an angular construct so it doesn't trigger the digest cycle. However, $interval
is, and thus it triggers the cycle.
Upvotes: 3
Reputation: 10390
You wont have access to $scope
in setInterval
, but you can get access to the scope by using:
var $myscope = angular.element([Some DOMElement]).scope();
then call the same code you have already followed by $digest()
:
$myscope.now = new Date().toLocaleTimeString();
$myscope.$digest(); // this will refresh the UI
Upvotes: 0