How to add restrict localStorage cart value only last clickable item


#1

Hi,
i’m developing one small ionic application. in this application i’m using cart. when i click button that item is added to cart. i need only last clickable item.before added items are automatically remove. how it is possible?
My controller code:
.controller(‘Demo’, function($scope,$state,mySharedService, $ionicActionSheet, BackendService, CartService) {

$scope.cart = CartService.loadCart();

$scope.doRefresh = function(){
BackendService.getFood()
.success(function(newItems) {
$scope.products = newItems;
})
.finally(function() {
$scope.$broadcast(‘scroll.refreshComplete’);
});
};

var addProductToCart = function(product){
$scope.cart.products.push(product);
CartService.saveCart($scope.cart);
};

$scope.addProduct = function(product){
$ionicActionSheet.show({
buttons: [
{ text: ‘Add to produce’ }
],
titleText: 'add to cart ’ + product.itemName,
cancelText: ‘Cancel’,
cancel: function() {
// add cancel code if needed …
},
buttonClicked: function(index) {
if(index == 0){
addProductToCart(product);
return true;
}
return true;
}
});
};

$scope.doRefresh();

})

My service code:
.factory(‘CartService’, [function () {
var svc = {};

svc.saveCart = function(cart){
window.localStorage.setItem(‘cart’, JSON.stringify(cart));
};

svc.loadCart = function(){
var cart = window.localStorage.getItem(‘cart’);
if(!cart){
return { products : [ ] }
}
return JSON.parse(cart);
};

svc.resetCart = function(){
var cart = { products : [ ] };
svc.saveCart(cart);
return cart;
};

svc.getTotal = function(cart){
var out = 0;
if(!cart || !cart.products || !angular.isArray(cart.products)){
return out;
}
for(var i=0; i < cart.products.length; i++){
out += cart.products[i].price;
}
return out;
}

return svc;

}])