我有以下代码:
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(未找到)
有人可以帮助我吗?
答案 0 :(得分:0)
也许你的平等功能不正确?你能创建一个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();
}
答案 1 :(得分:0)
这不仅仅是一个阵列吗?为什么不把它清空呢?
// [BUTTON] Remove bundle
$scope.removeBundle = function() {
$rootScope.selectedBundle = [];
$modalInstance.close();
}
采取2:您不需要搜索value
的索引 - 它由angular.forEach
提供。在迭代对象时,获取key
,但对于数组,您获得index
$scope.removeBundle = function() {
angular.forEach($rootScope.selectedBundle,function(value, index){
$rootScope.selectedBundle.splice(index, 1);
});
$modalInstance.close();
}