首页 > 解决方案 > 无法从 Angular 上的购物车中删除商品

问题描述

我需要按清除按钮删除所有添加到购物车的物品。我开始编写一个函数,但它拒绝工作。我认为错误是我没有将物品推到购物车。我该怎么做这两件事?无论如何,如果您发现任何错误,请指出。

angular.module('TransactionApp', [])
    .controller('TransactionsCtrl', function($scope) {
        $scope.title = 'Add to cart';

        $scope.itemsArray = [{
                price: 50,
                name: "Whey protein",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 60,
                name: "Protein bar",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 35,
                name: "BCAA",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 50,
                name: "Whey protein",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 60,
                name: "Protein bar",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 80,
                name: "BCAA",
                img: 'img/item-1.png',
                quantity: 0
            }

        ];

        $scope.addTo = function(item) {
            item.quantity += 1;
        }

        $scope.getCost = function(item) {
            return item.quantity * item.price;

        }

        $scope.cart = [];

        $scope.getTotal = function() {
            return $scope.itemsArray.reduce((a, b) => a + b.price * b.quantity, 0);
        }

        $scope.clearCart = function() {
            return $scope.cart.length = 0;
        };
    });

标签: javascriptangularjs

解决方案


应该

$scope.clearCart = function() {
  $scope.cart = [];
};

推荐阅读