AngularJS:在$ HTTP成功的回调范围的问题回调、范围、问题、AngularJS

2023-09-13 05:05:35 作者:秋奈櫻舞、

我使用PHP来获取数据到我的工厂,正确地显示在控制器内成功回调函数。然而,即使返回的数据分配给$ scope.customers后,它的不存在,如果我做回调后的console.log($ scope.customers),和我的观点的[NG重复]没有拿起它无论是。

任何想法,为什么我的数据的范围会,如果我指派返回数据,以我的$ scope对象仅限于刚刚成功回调里面呢?

  VAR customersController =功能($范围,customersFactory){  $ scope.customers = [];  customersFactory.getAllData()    .success(功能(客户){      $ scope.customers =客户;      的console.log($ scope.customers); //用正确的数据对象    }); //没有错误,所以只显示快乐路径  的console.log($ scope.customers); //空[]};customersModule.controller('customersController',['$范围,customersFactory',customersController]); 

解决方案

$ HTTP功能同步发生。因此,以后打电话的console.log的 customersFactory.getAllData 将永远是空的。

的console.log($ scope.customers); //用正确的数据对象

实际发生后

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

您可以信任成功回调设置 $ scope.customers 正确,你只需要你的网站来了解它以后会发生。如果您需要scope.customers视图加载之前要填充,可以考虑使用控制器上的决心。

AngularJS范例入门

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

解决方案

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