【问题标题】:Angular JS Promise - Binding inside a forEach loopAngular JS Promise - 在 forEach 循环内绑定
【发布时间】:2014-12-02 21:51:50
【问题描述】:

我正在使用angular.forEach 迭代一个数组,对于数组中的每个值,我使用 GET/ 来检索它的名称(数组包含键),然后将该名称推送到另一个数组中。这个新数组正在下拉框 (ngOptions) 中使用。

我遇到的问题是下拉菜单是在 GET/ 响应到达之前创建的,所以它只显示空白选项,然后当它们到达时,它会显示每个下拉菜单中的所有选项。

我有以下代码:

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 = []; 代码,因此它只是将所有三个罐的完整数组推入每个罐。

请问有什么提示/建议吗?谢谢。

【问题讨论】:

    标签: arrays angularjs binding iteration promise


    【解决方案1】:

    看来我已经修复了它...有人可以确认这是一个好习惯吗?每次我根据锅中的 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);
    

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 2023-03-20
      • 2020-11-13
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      相关资源
      最近更新 更多