繁体   English   中英

从数组中删除对象

[英]Remove object from array

我有以下代码:

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();
   }
});

当我使用时:

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

在$ scope.selectBundle中,返回正确位置

现在,当我在$ scope.removeBundle中使用时,总是返回-1(未找到)

有人可以帮我吗?

也许您的相等函数不正确? 您可以创建一个jsFiddle或Plunker吗? 同时,请尝试将要删除的内容传递给调用函数,例如:

// [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();
}

不仅仅是数组吗? 为什么不只是清空呢?

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

作为2:您无需搜索value索引-它由angular.forEach提供。 当遍历对象时,您的get key ,但是对于数组,您的get index

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

   $modalInstance.close();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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