Reputation: 1700
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)
Upvotes: 0
Views: 201
Reputation: 8970
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);
} );
Upvotes: 2
Reputation: 1676
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);
Upvotes: 0
Reputation: 1700
Ok, I've found the answer: wrap $scope.foo['bar']++
into
$scope.$apply(function({
$scope.foo['bar']++
}))
Upvotes: -1