简体   繁体   中英

using slice in angularjs array

In my angularjs app, i need to manually remove or add old/new data from a data array (service is executed in a loop). For remove, i use slice(); but there is a problem: the item is correctly removed but execVerif_distant(); is not executed for the next item. With my actual code, execVerif_distant(); is executed for each item only half a time. For example, if i need to remove entire array, only half is removed.

            // start the loop, search in local datas
            angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
                execVerif_local(itemLocalCages.url);
            });

            function execVerif_local(identifiant) {
                var iterSearch_local = 0;
                angular.forEach(responseZS, function(itemDistantCages) {
                    if (itemDistantCages.url == identifiant) {
                        iterSearch_local++;
                    }
                });
                // if we not find the local datas in distant datas
                if (iterSearch_local == 0) {
                    // verifItem(); call
                    verifItem('remove', identifiant);
                }
            }




                // verifItem();
                function verifItem(action, url) {
                    if (action == 'remove') {
                        var iIndex = -1;
                        angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
                            iIndex++;
                            if (itemLocalCages.url == url) {
                                $scope.seaDocument.datas.cages.splice(iIndex,1);
                            }
                        });
                    } else {
                        // do nothing
                    }
                }

what's wrong ?

The problem is that the foreach is iterating over the same object you are removing things from. To avoid this behavior clone the object you are iterating before the loop and work with them as separate:

// ... code
var arrCopy = $scope.seaDocument.datas.cages.slice(); //this will create a deep copy.

angular.forEach(arrCopy, function(itemLocalCages) {
  iIndex++;
  if (itemLocalCages.url == url) {
    $scope.seaDocument.datas.cages.splice(iIndex,1);
  }
});
//... more code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM