[英]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.