dopatraman
dopatraman

Reputation: 13908

mismatch between updating model and internal angular update

Here is something im trying to do. I'm setting an interval in my controller that updates a model:

myapp.js
----------
$scope.myModel = myArray[$scope.currentIndex];
var changeModel = function() {
    $scope.currentIndex += 1; //increment index
    $scope.myModel = myArray[$scope.currentIndex]; //reset model
}
setInterval(changeModel, 1000);

Then I have a template that access that updated model:

my-template.html
-----------------
<div>{{$scope.myModel}}</div>

What I see happening is that the template is not refreshed every second. It is not event refreshed consistently. When looking at the page, the text in the div will jump suddenly, sometimes after less than a second. I suspect this has to do with a mismatch between my own changeModel method and the internal view-updating that angular does. Has anyone else encountered this problem? If so, how did you solve it?

Upvotes: 0

Views: 113

Answers (1)

Patrick
Patrick

Reputation: 6958

Since setInterval code runs outside of angular, you will need to run a scope.$apply (or more safely scope.$evalAsync). A quick jsfiddle to demonstrate.

Try this:

$scope.myModel = myArray[$scope.currentIndex];
var changeModel = function() {
    $scope.currentIndex += 1; //increment index
    $scope.myModel = myArray[$scope.currentIndex]; //reset model

    //This will make sure angular runs a digest loop which will update your data.
    $scope.$evalAsync();
}
setInterval(changeModel, 1000);

$interval is available in version 1.2 and would be more appropriate as this would no longer require an $evalAsync to run a digest loop. Example of using $interval.

Upvotes: 1

Related Questions