AngularJS : Scope issue in $http success callback

偶尔善良 提交于 2019-12-10 20:25:23

问题


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]);

回答1:


$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.




回答2:


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.



来源:https://stackoverflow.com/questions/25043534/angularjs-scope-issue-in-http-success-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!