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