2013-02-20 40 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); 
}