1

I have a piece of $scope text that should update dynamically.

<span ng-bind="user.balance"></span>

after pushing a button, new value of balance is received and should be displayed here.

$http.post('/transaction/send', transaction).success(function(sender) {
          console.log("http response");
          $scope.user = sender;
          console.log($scope.user.balance);
          $timeout(function() {$scope.$apply(); console.log("apply used");}, 1000);
        });

In console log anything is received and displayed properly, but it still doesn't update scope in the view. What am I doing wrong? I'm using $timeout to get rid of "$digest is already in use"

user3081123
  • 425
  • 6
  • 15
  • 2
    You should not put `$scope.$apply()` there, actually it is not needed as well.. Digest cycle will be triggered after success callback.. Your issue could be elsewhere – PSL Aug 26 '14 at 13:03
  • 1
    I think I remember seeing a similar scenario and `angular.extend($scope.user, sender);` would be used instead of `$scope.user = sender;` that way, you would merge the objects instead of assigning a new one. – Maxime Morin Aug 26 '14 at 13:09
  • Worked amazing, sir. You can make it an answer so I can mark it. – user3081123 Aug 26 '14 at 13:11

1 Answers1

2

You should use angular.extend(dst, src) instead of assigning a new object to your $scope.user variable. By doing so, you will be merging the new properties into your older object; this will keep your binding working. In the end, you should have something like this:

$http.post('/transaction/send', transaction).success(function(sender) {
      console.log("http response");
      angular.extend($scope.user, sender);
      console.log($scope.user.balance);
});

Mind you, this only does a shallow merge, for a deep merge, you should look at this discussion or this one.

Community
  • 1
  • 1
Maxime Morin
  • 2,008
  • 1
  • 21
  • 26
  • this feels like a workaround. is there a better way to write the binding? – Robert Levy Aug 26 '14 at 13:31
  • @RobertLevy I personally don't see it as a workaround. I also don't know if there's a better way to write the binding to solve this issue, but if there is, I'm interested in knowing how. :) – Maxime Morin Aug 26 '14 at 13:52