0

Why doesn't this code work? I am assigning a value to the $scope, when the page renders, I see 5 but once the timer fires, the value isn't updated. I am wondering what kind of object the primitive 5 needs to become so that Angular will watch it for changes. Also, if there is a proper way to do this kind of thing it would be nice to know.

app.controller('Total', ['$scope', function($scope) {
    $scope.total = 5;
    setTimeout(function() {
      $scope.total = 1300;
    }, 3000);
  }
]);
buddyw
  • 43
  • 7

2 Answers2

0

The problem is that Angular didn't know I assigned a new value to $scope.total, see the StackOverflow answer for more information on how binding works. The solution is to use $scope.$apply and wrap the assignment in a function. Angular will then compare the previous value to the new value to fire the correct functions, see an explanation with sample code of $scope.$apply here.

Solution:

app.controller('Total', ['$scope', function($scope) {
    $scope.total = 5;
    setTimeout(function() {
      $scope.$apply(function() {
        $scope.total = 1300;
      });
    }, 3000);
  }
]);
Community
  • 1
  • 1
buddyw
  • 43
  • 7
0

use $timeout, then you don't need to use $apply.

Different question, but the same answer here, ng-repeat not growing with object

Community
  • 1
  • 1
allenhwkim
  • 27,270
  • 18
  • 89
  • 122
  • This solution is the correct choice to do what I was attempting but didn't help me understand my problem better. Thanks for the reply! – buddyw Jan 31 '14 at 18:50