Keith DC
Keith DC

Reputation: 673

AngularJS : Scope issue in $http success callback

I'm using PHP to get data into my factory, which shows correctly in the success callback function within the controller. However, even after assigning the returned data to $scope.customers, it's not there if I do a console.log($scope.customers) after the callbacks, and my view's [ng-repeat] isn't picking it up either.

Any idea why the scope of my data would be restricted to just inside the success callback if I'm assigning the returned data to my $scope object?

var customersController = function($scope, customersFactory) {
  $scope.customers = [];
  customersFactory.getAllData()
    .success(function(customers) {
      $scope.customers = customers;
      console.log($scope.customers); // Object with correct data
    }); // No errors so only showing happy path
  console.log($scope.customers); // empty []
};
customersModule.controller('customersController', ['$scope', 'customersFactory', customersController]);

Upvotes: 3

Views: 1360

Answers (2)

Fourth
Fourth

Reputation: 9351

$http functions happen asynchronously. Thus, calling console.log after the customersFactory.getAllData will always be empty.

console.log($scope.customers); // Object with correct data

is actually happening AFTER

console.log($scope.customers); // empty []

You can trust the success callback to set $scope.customers correctly, you just need your site to understand that it will happen later. If you NEED scope.customers to be populated before the view loads, consider using a resolve on the controller.

Upvotes: 2

Jonathan Aquino
Jonathan Aquino

Reputation: 3870

Isn't

console.log($scope.customers); // empty []

executing before

console.log($scope.customers); // Object with correct data

?

The second one is in a success() callback so it could execute much later than the first one.

Upvotes: 0

Related Questions