You call the deleteFromCart()
function, shown in Listing 28.24, from the cart template when the user clicks the Remove button. It iterates through the items in customer.cart
, and if it finds the item, it uses the array.slice(index,1)
method to delete it from the array.
Once the item is removed from $scope.customer.cart
, 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, this switches to cart.html
; on failure, an alert window appears.
067 $scope.deleteFromCart = function(productId){
068 for(var i=0; i<$scope.customer.cart.length; i++){
069 var item = $scope.customer.cart[i];
070 if (item.product[0]._id== productId){
071 $scope.customer.cart.splice(i,1);
072 break;
073 }
074 }
075 $http.post('/customers/update/cart',
076 { updatedCart: $scope.customer.cart })
077 .success(function(data, status, headers, config) {
078 $scope.content = '/static/cart.html';
079 })
080 .error(function(data, status, headers, config) {
081 $window.alert(data);
082 });
083 };