I am building small utility to handle shopping cart of user in AngularJS.
Below is my cart-service.js file definition.
var myStoreCartService = angular.module("myStoreCartService", []);
myStoreCartService.factory('Cart', function() {
var userCart=[];
var cartSummary=[];
return{
addItemToCart: function(item) {
userCart.push(item);
},
retrieveCart: function(){
return userCart;
},
getCartSummary: function(){
cartSummary=[];
for (var key in userCart){
var currentItem={"productname":"","price":""};
if (userCart.hasOwnProperty(key)){
currentItem["productname"]=userCart[key].productname;
currentItem["price"]=userCart[key].price;
cartSummary.push(currentItem);
continue;
};
}
return cartSummary;
},
getCurrentTotal: function(){
alert("Sum function called "+ cartSummary);
var currentSum=0;
for (var key in cartSummary)
{
if (cartSummary.hasOwnProperty(key))
{
// get sum
currentSum = currentSum+parseInt(cartSummary[key].price);
alert(currentSum+" is current sum")
continue;
};
}
return currentSum;
}
}
});
Below is method used to update the cart of page.(Defined in controller of page)
function addItemToCartHelper(data){
Cart.addItemToCart(data);
$scope.cart=Cart.retrieveCart();
$scope.cartLength=$scope.cart.length;
$scope.userCartSummary=Cart.getCurrentTotal();
$scope.userCartSummaryFromService=Cart.getCartSummary();
}
My issue is I am not getting correct total sum of the price ,I always get one less item added to my price.
I do realize that, my function to sum the total cost should run only after my cart summary has been updated , but in my case it runs before cart summary update function has been launched.
I need a way to ensure that, cart summary has finished execution before totaling function runs.
addItemToCartHelperthen...? They're both synchronous calls as far as I can tell.