简体   繁体   English

无法从Angular上的购物车中删除商品

[英]can't delete items from cart on Angular

I need to delete all the added to cart items by pressing button clear. 我需要通过按清除按钮来删除所有添加到购物车中的物品。 I started to write a function but it refused to work. 我开始写一个函数,但是它拒绝工作。 I consider the mistake is that I didn't push items to cart. 我认为错误是我没有将物品推入购物车。 How can I do these 2 things ? 我该怎么做这两件事? Anyway, if you see any mistakes, please, mention. 无论如何,如果您发现任何错误,请提及。

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;
        };
    });

Juse reset the items in the array, Juse重置数组中的项目,

   $scope.cart = [];

you do not need to return anything, and you can get the count by using length. 您不需要返回任何内容,并且可以使用length获得计数。

should be 应该

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

To make it empty use following: 要使其为空,请使用以下命令:

$scope.cart = [];

or to reduce one by one: 或一一减少:

$scope.cart.slice(start, end);//start is an index from where you want to delete and the end is number which represents how many to delete.

To insert something on the array at last index, you do require to push: 要在数组的最后一个索引处插入某些内容,您需要执行以下操作:

$scope.cart.push(item);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM