Rohit Ghotkar Rohit Ghotkar - 1 month ago 19
AngularJS Question

angular js - dynamically add Data in local storage

I am new to

angular js
, I am using angular js local storage in my project.
I want to add data object dynamically on button click. How can I do that?

My function is :

$scope.saveItem=function(){
var dataobj={'itemCode':vm.person1.selected.itemCode,
'itemName':'name',
'qty':'1',
'price':'2',
'total':1 * 2,
'comment':'comment',
};
localStorageService.set('order',dataobj);
}


i enter static data here but this data will be dynamic when i add new item.
and I want previous data and newly entered data in local storage. Please help me

Answer

I don't know why using a service for localStorage, you can simply use localStorage native API. When you add some item just do something like this :

var order = localStorage.getItem('order');
if(order) {
   localStorage.setItem('previousOrder', order);
}
localStorage.setItem('order', NEW_ORDER_DATA_HERE);

NOTE : A storage item must be a DOMString so think about JSON.stringify and JSON.parse your data before storing and fetching them.