简体   繁体   中英

Remove object from array

I have following code:

app.controller('modalController', function($scope, $http,$modalInstance, $rootScope, items){

   // Get info
   $http.post('/ajax/bundle', {'items':items}).success(function(data){
       $scope.info = data['info'];
   });

   // [BUTTON] Add Bundle
   $scope.selectBundle = function() {

        // Push the info to the cart
        $rootScope.cart.push($scope.info);
        // simplified info
        $rootScope.selectedBundle.push(items)
        // Close modal
        $modalInstance.close();
   }

   // [BUTTON] Remove bundle
   $scope.removeBundle = function() {
        // Run all bundles
        angular.forEach($rootScope.selectedBundle,function(value, key){
           // Exists
           if (angular.equals(value,items)) {
               // Remove simplified
               $rootScope.selectedBundle.splice($rootScope.selectedBundle.indexOf(value), 1);
               // remove form cart
               // $rootScope.cart.splice($rootScope.cart.indexOf($scope.info), 1);
           }
       });

       // Close modal
       $modalInstance.close();
   }
});

When i use:

console.log($rootScope.cart);
console.log($scope.dados);
console.log($rootScope.cart.indexOf($scope.dados));

in $scope.selectBundle, returns correct position

Now, when i use in $scope.removeBundle, always returns -1 (not found)

Someone can help me?

Maybe your equality function is incorrect? Could you create a jsFiddle or Plunker? In the meantime.. try passing the thing you want removed into the calling function, like such:

// [BUTTON] Remove bundle
$scope.removeBundle = function(someItemToRemove) {
    console.log(someItemToRemove); // pass item to remove
    angular.forEach($rootScope.selectedBundle, function(value, key){
       // Exists
       if (value === someItemToRemove) {
           $rootScope.selectedBundle.splice($rootScope.selectedBundle.indexOf(value), 1);
       }
    });

    // Close modal
    $modalInstance.close();
}

Is not it just an array? Why not just empty it ?

// [BUTTON] Remove bundle
$scope.removeBundle = function() {
     $rootScope.selectedBundle = [];
     $modalInstance.close();
}

Take 2: You don't need to search for index of value - it is supplied by angular.forEach . When iterating through object your get key , but for arrays your get index

$scope.removeBundle = function() {
    angular.forEach($rootScope.selectedBundle,function(value, index){
        $rootScope.selectedBundle.splice(index, 1);
    });

   $modalInstance.close();

}

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