Suresh Iyengar
Suresh Iyengar

Reputation: 59

Digest loop in Angular

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

Answers (2)

Tarun Dugar
Tarun Dugar

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

Glenn Ferrie
Glenn Ferrie

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

Related Questions