这是我的代码
$scope.cart = [];
$scope.addToCart = function (cat) {
var found = false;
$scope.cart.forEach(function (item) {
if (item.id === cat.product_id) {
item.quantity++;
found = true;
}
});
if (!found) {
$scope.cart.push(angular.extend({quantity: 1}, cat));
}
};
//remove from cart function
$scope.removeToCart = function (cat) {
console.log(cat.product_id);
var found = false;
$scope.cart.forEach(function (item) {
if (item.id === cat.product_id) {
item.quantity--;
found = true;
}
});
if (!found) {
$scope.cart.push(angular.extend({quantity: 1}, cat));
}
};
console.log($scope.cart);
$scope.getCartPrice = function () {
var total = 0;
$scope.cart.forEach(function (cat) {
total += cat.finalprice * cat.quantity;
});
return total;
};
最佳答案
可能您需要从removeToCart函数中删除此位:
if (!found) {
$scope.cart.push(angular.extend({quantity: 1}, cat));
}
如果在购物车中找不到“cat”,您总是会添加一个数量为 1 的猫。“addToCart”和“removeToCart”对我来说似乎是相同的,除了 item.quantity++ 和 item.quantity-- 行。
关于javascript - 从购物车中删除在 AngularJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36514036/