2014-10-08 52 views
0

我使用angular.forEach來遍歷數組,併爲數組中的每個值,我使用GET /來檢索它的名稱(數組包含鍵),然後將該名稱插入另一個陣列。這個新陣列正在下拉框中使用(ngOptions)。Angular JS Promise - 在forEach循環中綁定

我遇到的問題是在GET/response到達之前下拉菜單正在創建,所以它只顯示空白選項,然後當它們到達時,它會在每個下拉菜單中顯示所有選項。

我有以下代碼:

angular.forEach($scope.pots, function(value, key) { 
    $scope.selections = []; 
    angular.forEach(value, function(val, ky) { 
     if (ky === "selections") { 
      angular.forEach(val, function(v, k) { 
       $http.get('/selections/' + v).then(function(response) { 
        var response = response.data; 
        $scope.selection = response[0]; 
        $scope.selectionName = $scope.selection.name; 
        $scope.selections.push({name : $scope.selectionName}); 
        value["selectionNames"] = $scope.selections; 
       }) 

      }) 
     } 
    }) 
value["selectionNames"] = $scope.selections; 
console.log(value); 

所以我遍歷其中包含選擇列表盆的列表,使用GET /根據選擇的名單上獲得的名單和最後把它推入鍋的範圍。我在每個底池之後重置選區。

是什麼造成的問題是,所有的反應變量來一次,他們繞過$scope.selections = [];代碼,所以它只是推入每盆所有三個盆,整個陣列。

請提供任何提示/建議?謝謝。

回答

0

所以看起來我已經修好了......有人可以確認這是好的做法嗎?每次我根據pot(value)中的selectionNames值迭代時,我基本上都會重新創建$scope.selections

angular.forEach($scope.pots, function(value, key) { 
    $scope.selections = []; 
    angular.forEach(value, function(val, ky) { 
     if (ky === "selections") { 
      angular.forEach(val, function(v, k) { 
       $http.get('/selections/' + v).then(function(response) { 
        $scope.selections = []; 
        var response = response.data; 
        $scope.selection = response[0]; 
        $scope.selectionName = $scope.selection.name; 
        var currentSelections = value.selectionNames; 
        angular.forEach(currentSelections, function(csV, csK) { 
         $scope.selections.push(csv); 
        }) 
        $scope.selections.push({name : $scope.selectionName}); 
        value["selectionNames"] = $scope.selections; 
       }) 

      }) 
     } 
    }) 
value["selectionNames"] = $scope.selections; 
console.log(value);