I just need to store an array in localStorage and keep adding elements to that array so I could retrieve that stored array in my application. This must be a very simple thing to do with Angular Local Storage Module but it has got me troubling quite a bit, and I am hoping to get some help on this.
Following is the angular code I have that I am using to store a queries into localStorage using angular-local-storage module:
.factory('QueryService', ['localStorageService', function(localStorageService) {
var queries = [];
var factory = {};
factory.addQuery = function(query) {
queries.push(query);
localStorageService.set('queries', queries);
return localStorageService.get("queries");
};
return factory;
}])
Every time I add a query to the queries array, I get only the last element added returned in the result. So basically, localStorageService.get("queries") is giving me the last element added to the queries array.
Could somebody please help me understand that why am I getting only the last element I am adding to the queries array returned?
EDIT:
After each element I am adding to the queries array I am refreshing the browser.
stringifyandparseyour array for you. It's my understanding that localStorage only supports strings at this time. Therefore a conversion is needed (usually usingJSON.stringifyandJSON.parse). I wrote this up in a previous answer (outside of AngularJS). Not sure if the pre-built module covers that for you or not...queriesarray cleans up thequeriesarray?queriesarray to keep all the data (old and new) you'll need to first try and fetch the queries array from localStorage. If it exists, pull the existing content into an array, update the array and push all of the contents back into localStorage. If it's not in localStorage (indicating this is the first iteration of the process) create the array, fill in the new value and push it to localStorage. For all successive requests you'll need to repeat the first step.