javascript - 从购物车中删除在 AngularJS 中不起作用

标签 javascript html angularjs ionic-framework

这是我的代码

     $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/

相关文章:

javascript - 如何仅使用 javascript 加粗搜索内容?

javascript - 在浏览器中捕获 "Back"事件并加载不同的内容

javascript - 为什么 in_array() 总是返回 false(用户权限)?

html - 为什么 min-height :100% not work since declaring a doctype?

javascript - 单击下一个日期选择器时关闭日期选择器AngularJS

javascript - 在编写 Protractor spec.js 文件的测试用例中从浏览器获取 session 值

javascript - 如何处理在 puppeteer 中的 ajax 请求后加载的元素

javascript - jQuery 无法点击菜单

html - 如何防止浏览器尝试自动验证电子邮件地址字段?

javascript - 如何获取AngularJS中ng-repeat选项数组中的子值?