5

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?

1
  • 1
    Your pane should need to be {} object instead of array. Commented Nov 11, 2014 at 13:54

2 Answers 2

15

In 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();
Sign up to request clarification or add additional context in comments.

7 Comments

The setTimeout was just an example of the variable being changed. My script is actually more complex but the same issue applies (no setTimeout being used in my script).
@Coop The same logic applies. Any non-angular event must inform Angular that something has changed. Using $timeout applies to your example, but you could equally use $apply too
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.
Awesome! I never knew about $apply. Thanks for that.
$scope.$apply(); Saved me hours !! :)
|
3

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>

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.