Adding Items to the Cart

You call the addToCart() function, shown in Listing 28.23, from the template when the user clicks the Add to Cart button. It iterates through the items in the customer.cart, and if it finds that the item is there, it increments the quantity; otherwise, it adds the item to the customer.cart array with a quantity of 1.

Once $scope.customer is updated, you call an $http POST to the /customers/update/cart route to update the cart. This way, the cart is persistent and will be there even if the user closes the browser or navigates away. On success, the view switches to cart.html. On failure, an alert window appears.

Listing 28.23 cart_app.js-addToCart: Adding controller functions to handle adding and removing products from the cart


045     $scope.addToCart = function(productId){
046       var found = false;
047       for(var i=0; i<$scope.customer.cart.length; i++){
048         var item = $scope.customer.cart[i];
049         if (item.product[0]._id== productId){
050           item.quantity += 1;
051           found = true;
052         }
053       }
054       if (!found){
055         $scope.customer.cart.push({quantity: 1,
056                                    product: [this.product]});
057       }
058       $http.post('/customers/update/cart',
059                  { updatedCart: $scope.customer.cart })
060        .success(function(data, status, headers, config) {
061          $scope.content = '/static/cart.html';
062        })
063        .error(function(data, status, headers, config) {
064          $window.alert(data);
065        });
066     };


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset