Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scope variable updated in angular but change is not reflected to user

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?

like image 811
CaribouCode Avatar asked Nov 11 '14 13:11

CaribouCode


2 Answers

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();
like image 183
halilb Avatar answered Nov 07 '22 22:11

halilb


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>
like image 22
sylwester Avatar answered Nov 07 '22 23:11

sylwester