$ scope变量没有内容

时间:2014-10-04 08:37:53

标签: angularjs angularjs-scope

我有控制器和函数getData,如图所示。问题是for循环外的$ scope.results没有内容。在第二个http.get请求中,它有内容。

appControllers.controller('MyaSellerOrderCtrl', ['$scope', '$rootScope', 'Order', '$http',
    function($scope, $rootScope, Order, $http) {
        $scope.results = [];
        $scope.getData = function() {
               $http.get('api/orders/business/?user_id=' + $rootScope.user.user_id).success(function(data){
                    for (var i = 0; i < data.length; i++) {
                        $http.get('api/orders/seller/?business_id=' + data[i].business_id).success(function(data1){
                             // console.log(data1);        
                             $scope.results[i] = data1;
                       });
                     }
                     console.log($scope.results);
                });
         };
         $scope.getData();
     }]);

1 个答案:

答案 0 :(得分:1)

<强>解释

// STEP 1: your first request
 $http.get('api/orders/business/?user_id=' + $rootScope.user.user_id).success(function(data){
    // STEP 2 : your loop started
    for (var i = 0; i < data.length; i++) {
         // STEP 3 : you hit another request. it does not block any operation because it run asynchronously.
         // it also does not wait for any previous request to be completed.
        $http.get('api/orders/seller/?business_id=' + data[i].business_id).success(function(data1){
             // console.log(data1);
             $scope.results[i] = data1;
       });
     }
     // STEP 4: this doesn't wait for STEP 3 to complete because it [STEP 3 ] run asynchronously.
     // this lin run after for loop complete.
     console.log($scope.results); // so you get nothing here as STEP 3 is still running
});

参考

  1. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
  2. How to $http Synchronous call with AngularJS