如何让 AngularJs 购物车按预期工作

How to get AngularJs shopping cart to work as intended

我有一个简单的购物 AngularJs 应用程序。它按预期显示产品列表。您可以将产品添加到购物车,它会在购物车中显示产品名称和价格并更新总价。但是,如果您添加第二个产品,它不会显示第二个产品的名称。它只是将先前添加的产品的价格而不是新产品的价格添加到总价中。所以它不会 ng-repeat 你推入 $scope.cart 的产品。

这是我的 HTML:

 <div class="row">
   <div class="col-sm-8" ng-repeat="category in categories">
     <h2>{{category.categoryName}}</h2>
     <div ng-repeat="product in category.products track by $index">
       <div class="panel">
         <img ng-src="{{product.image}}">
         <h6>{{product.name}}</h6>
         <p>{{product.price}}</p>
         <button class="btn btn-sm" ng-click="addItemToCart(product)">Add to Cart</button> 
       </div>
     </div> 
   </div>
   <div class="col-sm-4">
     <ul class="list-group" ng-repeat="products in cart">
       <li class="list-group-item">
         {{products.name}} |{{products.count}}| {{products.price*products.count}} 
         <input class="btn btn-sm btn-danger" type="button" ng-click="removeItemCart(products)" value="Remove" />               
       </li>
       <h5>Number of items in cart: {{productsNumber}}</h5>
     </ul>
     <h4>Total: R{{total}}.</h4>
     <button class="btn btn-sm btn-success">Checkout</button>
   </div>
 </div>
</div> 

这是我的 AngularJs:

(function(){

    var app = angular.module('myApp', ['ngCookies']);

    app.controller('productsCtrl', ['$scope','$cookies', function($scope,$cookies){

        $scope.categories = productsData;
        // Add ids to the array objects //
        $scope.categories.forEach( function(d, i){ d.id = i+1; });
        $scope.cart = [];
        $scope.total = 0;
        $scope.productsNumber = $scope.cart.length;

        if (!angular.isUndefined($cookies.get('cart'))) {
            $scope.cart =  $cookies.getObject('cart');
        }

        $scope.addItemToCart = function(product){

            if ($scope.cart.length === 0){
                product.count = 1;
                $scope.cart.push(product);
            } else {
                var repeat = false;
                for(var i = 0; i< $scope.cart.length; i++){
                    if($scope.cart[i].id === product.id){
                        repeat = true;
                        $scope.cart[i].count +=1;
                    }
                }
                if (!repeat) {
                    product.count = 1;
                    $scope.cart.push(product);  
                }
            }
            var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + 1);
            $cookies.putObject('cart', $scope.cart,  {'expires': expireDate});
            $scope.cart = $cookies.getObject('cart');

            $scope.total += parseFloat(product.price);
            $cookies.put('total', $scope.total,  {'expires': expireDate});
        };

        $scope.removeItemCart = function(product){

            if(product.count > 1){
                product.count -= 1;
                var expireDate = new Date();
                expireDate.setDate(expireDate.getDate() + 1);
                $cookies.putObject('cart', $scope.cart, {'expires': expireDate});
                $scope.cart = $cookies.getObject('cart');
            }
            else if(product.count === 1){
                var index = $scope.cart.indexOf(product);
                $scope.cart.splice(index);
                expireDate = new Date();
                expireDate.setDate(expireDate.getDate() + 1);
                $cookies.putObject('cart', $scope.cart, {'expires': expireDate});
                $scope.cart = $cookies.getObject('cart');

            }

            $scope.total -= parseFloat(product.price);
            $cookies.put('total', $scope.total,  {'expires': expireDate});

        };

    }]);

    var productsData = [
    {
        categoryName: "Gas Cylinders",
        products: [
        {
            name: "15kg Gas Cylinder",
            image: "images/gas4.jpg",
            price: 50
        },
        {
            name: "DEFY 4 Burner Gas Stove",
            image: "images/stove2.jpg",
            price: 90
        }
        ]
    }, 
    {
        categoryName: "Electronics",
        products: [
        {
            name: "Samsung Galaxy J4 Core",
            image: "images/j4-core.jpg",
            price: 100
        },
        {
            name: "40'' FHD Hisense TV",
            image: "images/tv2.jpg",
            price: 200
        }
        ]
    } 
    ];

})();

我曾尝试将产品 ID 动态添加到 $scope.cart,但没有用。

我看到的第一个问题是,当您在此行中添加 id 时: $scope.categories.forEach( function(d, i){ d.id = i+1; });它在类别级别而不是在其中的产品数组中添加 id。 productsData 是数组的数组。内部数组包含客户将添加到购物车的产品,它应该有 ID。不在外部阵列级别。

所以为产品分配 ID 的逻辑应该改变。否则基于 ID 的 JS 代码将失败。