Reputation: 151206
If I have the following AngularJS code inside the controller:
$scope.s = "ha ha";
$interval(function() {
$scope.s = "hmm ha ha " + new Date().getTime();
}, 1000);
Then it will change the model, as well as make the 2-way binding work, so on the screen, any
{{ s }}
will show a new string every second.
But what after using setInterval()
... I used that and it won't update the view... I think it should be changing $scope.s
, but why is it not updating the view while $interval()
will?
(the same if it is $timeout()
vs setTimeout()
).
Upvotes: 1
Views: 95
Reputation: 692131
Because when using setInterval, angular has no way to know that the callback function has been called and has updated the scope, so it doesn't know that it must reevaluate the expressions in the view and refresh the DOM.
When using $interval, which is an angular service, angular knows when the callback function is called, and thus knows that it must reevaluate the expressions after the call, because the scope may have changed.
You can tell angular that you modified the scope in a setInterval callback function by using $scope.$apply()
.
Upvotes: 4