2013-02-20 108 views
-1

我试图从多个来源的数据读取到AngularJS控制器像这样 -

var Controller = function ($scope, $http) { 
    var load = { 
     somekey: "/data/a.json", 
     someotherkey: "/data/b.json", 
     yetanotherkey: "http://restapi" 
    } 
    for (var i in load) { 
     $http({ 
      url: load[i], 
      method: 'GET' 
     }).success(function (data, status, headers, config) { 
      $scope[i] = data; // <<---- this does not point to the right value of i 
     }).error(function (data, status, headers, config){ 
      $scope[i] = "Error getting content for " + i; 
     }); 
    } 
} 

但是这个代码似乎没有工作,因为在循环而可变i内容改变回调仍然在执行(即HTTP请求没有完成循环遍历字典中的所有值的时间),因此只更新最后一个值i,并且不使用所有其他值。

我该如何解决这个问题?

回答

1

我想正确的方法来编写循环是 - 或者

Object.keys(load).forEach(function (element, index, array) { 
    $http({ 
     url: load[element], 
     method: 'GET' 
    }).success(function (data, status, headers, config) { 
     $scope[element] = data; 
    }).error(function (data, status, headers, config){ 
     $scope[element] = "Error getting content for " + i; 
    }); 
}); 
+1

是的,它是在一个封闭。但是你可以使用['angular.forEach'](http://docs.angularjs.org/api/angular.forEach)来保存一些击键。 – 2013-02-20 18:30:15

0

,当然,做一个简单的封闭自己:

for (var item in load) { 
    (function(i) { 
     $http({ 
      url: load[i], 
      method: 'GET' 
     }).success(function (data, status, headers, config) { 
      $scope[i] = data; // <<---- this does not point to the right value of i 
     }).error(function (data, status, headers, config){ 
      $scope[i] = "Error getting content for " + i; 
     }); 
    })(item); 
}