2014-10-08 67 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);