AngularJS:在$ HTTP成功的回调范围的问题 [英] AngularJS : Scope issue in $http success callback

查看:266
本文介绍了AngularJS:在$ HTTP成功的回调范围的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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视图加载之前要填充,可以考虑使用控制器上的决心。

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.

这篇关于AngularJS:在$ HTTP成功的回调范围的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆