0

I have a promise that I thought should work, but isn't. The server returns a 200 and the javascript receives the data with no errors being generated, but the scope in the view is not updated. I'm not sure what's wrong as I'm still new to Angular promises. Any help would be great. Thanks.

I have a service that has two methods handles the http callback...

this.addresses = [];

this.getAddresses = function() {
  var deferred = $q.defer();

  addresses = [];

  $http({
    method: "GET",
    url: '/list_addresses'
  }).success(function(data, status, headers, config) {

      for (x = 0; x < data[':addresses'].length; x++) {
        address = {};

        address['balance'] = data[':addresses'][x][':balance'];

        address['address'] = data[':addresses'][x][':address'];

        address['label'] = data[':addresses'][x][':label'];

        address['total_received'] = data[':addresses'][x][':total_received'];

        addresses.push(address);
      }
      deferred.resolve(addresses);
    }).error(function(data, status, headers, config) {

      console.log(data)

    });

  return deferred.promise;
};

this.loadAccount = function() {
  this.getAddresses()
    .then(
     function(result){
       this.addresses = result;
  }, function(error){
       // error
  }, function(percentComplete){
  });
};

Now in my controller that has the above service injected in it

$scope.awesomeServiceIcreated = awesomeServiceIcreated;

$scope.loadAccount = function() {
  AwesomeServiceICreated.loadAccount();
};

$scope.$watch('awesomeServiceIcreated.addresses', function(newValue) {
  $scope.addresses = newValue;
});

In my views

<button ng-click="loadAccount()">Click me</button>

<div>{{addresses}}</div>
thank_you
  • 11,001
  • 19
  • 101
  • 185

1 Answers1

1

Check this question: "this" inside an anonymous function?

this keyword loses it's context inside an asynchronous callback.

Inside the asynchronous callback console.log(this === window) // true

Solution:

this.loadAccount = function() {
  var _this = this;
  this.getAddresses()
    .then(
     function(result){
       _this.addresses = result;
  }, function(error){
       // error
  }, function(percentComplete){
  });
};
Community
  • 1
  • 1
Ilan Frumer
  • 32,059
  • 8
  • 70
  • 84