0

I am trying to do the following:

angular.module("controllers", [])
    .controller("FooController", function($scope) {
        $scope.foo = {};
        $scope.foo['bar'] = 0;
        setInterval(function(){
            $scope.foo['bar']++;
        }, 100);
} );

And then, I display the value of foo.bar in my view using

<div> {{ foo.bar }} </div>

The initial value is displayed correctly, but it is never updated. The callback within setInterval is called correctly and the value of bar is updated in javascript.

How can I programmatically "push" my data into the model? (in my real app I'll be pushing data from the server via websockets / atmosphere)

1
  • 1
    $interval Commented May 20, 2014 at 9:56

3 Answers 3

2

If you use the angular $interval service instead of setInterval. Then you will not need to call $scope.$apply.

angular.module("controllers", [])
    .controller("FooController", function($scope, $interval) {
        $scope.foo = {};
        $scope.foo['bar'] = 0;
        $interval(function(){
            $scope.foo['bar']++;
        }, 100);
} );
Sign up to request clarification or add additional context in comments.

1 Comment

The question is more about a general "push", not of solving the dummy setTimeout (as I wrote, the real app will use websocket push, in which case the apply will work, while interval won't be useful)
0

You have to trigger a new digest cycle, in which Angular will check all the registered watches and update the view for objects that changed value. You can do it by calling $scope.$apply, which will trigger the digest cycle for you.

 setInterval(function(){
     $scope.$apply(function() {
         $scope.foo.bar++;
     })
 }, 100);

1 Comment

Why the downvote? This is equivalent to $interval. It's not incorrect.
-1

Ok, I've found the answer: wrap $scope.foo['bar']++ into

$scope.$apply(function({
    $scope.foo['bar']++
}))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.