I have some angular variables set like so:
$scope.pane = [];
$scope.pane.count = 0;
$scope.pane.max = 5;
Then I display the variables in the HTML like this:
{{pane.count}}
This works fine and displays 0
as expected.
Now if I update the variable at any point, the update does happen (I can see using console.log) but the printed version in the HTML does not update.
E.g.
setTimeout(function(){
$scope.pane.count = 1;
},1000);
I am using Angular v1.3. What am I doing wrong?
I have some angular variables set like so:
$scope.pane = [];
$scope.pane.count = 0;
$scope.pane.max = 5;
Then I display the variables in the HTML like this:
{{pane.count}}
This works fine and displays 0
as expected.
Now if I update the variable at any point, the update does happen (I can see using console.log) but the printed version in the HTML does not update.
E.g.
setTimeout(function(){
$scope.pane.count = 1;
},1000);
I am using Angular v1.3. What am I doing wrong?
Share Improve this question asked Nov 11, 2014 at 13:48 CaribouCodeCaribouCode 14.4k33 gold badges111 silver badges183 bronze badges 1 |2 Answers
Reset to default 15In order to let angular know about changes, you have to use angular wrapper for timeout.
Try this:
$timeout(function() {
$scope.pane.count = 1;
}, 1000);
Generally, when you have a structure outside angular world(such as jQuery plugin) that changes values, you have to call $scope.$apply() to let angular know about them.
$scope.$apply();
setTimeout is outside angularjs scope so you need to use $scope.$apply or $timout please see sample demo below
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $timeout) {
$scope.pane = [];
$scope.pane.count = 0;
$scope.pane.count2 = 0;
$scope.pane.max = 5;
setTimeout(function() {
$scope.$apply(function() {
$scope.pane.count = 1;
})
}, 1000);
$timeout(function() {
$scope.pane.count2 = 5;
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<h3>setTimeout</h3>
Count 1: {{pane.count}}<br/>
<h3>$timeout</h3>
Count 2: {{pane.count2}}
</div>
</div>
pane
should need to be{}
object instead of array. – Rahil Wazir Commented Nov 11, 2014 at 13:54