$localStorage Array gets overwrite the array value


#1

I am developing an add to cart app. Also, I am using $localStorage to store an items array. My array data gets stored in the $localStorage.

Whenever I go back to the previous page and add a new item array, the $localStorage gets overwritten with the previous stored array.

This is what I have tried:

$scope.invoice = {
items: [] };

$scope.addItem = function() {
$scope.invoice.items.push({
id: $stateParams.foodId,
qty: $scope.count,
description: $scope.ar_name,
cost: $scope.total
});

localStorage.setItem(“invoice”, JSON.stringify($scope.invoice.items));

$scope.cartData = localStorage.getItem(“invoice”);


#2

I do not see any problem in your code, you could create a codepen? I left a factory for future use you have in your application. I do not understand is what happens, that mistake is having

.factory('serviceExample',['$http',function($http){
 return {
    set:function(key,value){
      return localStorage.setItem(key,JSON.stringify(value));
    },
    get:function(key){
      return JSON.parse(localStorage.getItem(key));
    },
    destroy:function(key){
      return localStorage.removeItem(key);
    },
 };
}])