Reputation: 165
I am working on a prototype that stores products (like a favourite) into localStorage but I am struggling to check to see if an item already exists in localStorage so its not added again.
Where would the best place be to check for a duplicate entry and handle it gracefully?
My sample controller is below:
function dCtrl($scope, $filter) {
$scope.d = [
{id:'1',d_name:'Product 1',colour:'Blue'},
{id:'2',d_name:'Product 2',colour:'Red'},
{id:'3',d_name:'Product 3',colour:'Cream'},
{id:'4',d_name:'Product 4',colour:'White'},
{id:'5',d_name:'Product 5',colour:'Green'},
{id:'6',d_name:'Product 6',colour:'Black'},
{id:'7',d_name:'Product 7',colour:'Purple'},
{id:'8',d_name:'Product 8',colour:'Grey'},
{id:'9',d_name:'Product 9',colour:'Yellow'},
{id:'10',d_name:'Product 10',colour:'Indigo'}
];
$scope.getDetails = function (id, favDresses) {
//get the object of the item clicked
single_object = $filter('filter')($scope.d, {id:id})[0];
// If you want to see the result, check console.log
console.log(single_object);
console.log('ID:' + id + ' - save this object to localStorage');
//set localstorage var
var storage = localStorage.getItem('newfavdresses');
//check to see if the localStorage array is empty (not null)
if(storage != null) {
//if it isnt, parse the string
favDresses = JSON.parse(localStorage.getItem('newfavdresses'));
//push into the array
favDresses.push(single_object);
//set the item in localstorage
localStorage.setItem("newfavdresses",JSON.stringify(favDresses));
} else {
//if the array is null, create it
var favDresses = [];
//and push the item into it
favDresses.push(single_object);
//set the item in local storage
localStorage.setItem("newfavdresses",JSON.stringify(favDresses));
}
}
$scope.clearStorage = function() {
localStorage.clear();
alert('Local Storage Cleared');
}
//get localStorage items
var dresses = localStorage.getItem("newfavdresses");
dresses = JSON.parse(dresses);
console.log(dresses);
}
jsFiddle demo - https://jsfiddle.net/dwhiteside86/Lt7aP/2261/
Upvotes: 0
Views: 857
Reputation: 3470
Look at https://github.com/grevory/angular-local-storage, I believe it will solve all your issues. This library will bind your scope property to local storage so You'll dont care about how it stores.
Upvotes: 0
Reputation: 171669
My suggestion is work with live javascript array stored in service.
You would load this array from localStorage when service initializes or set to empty array if nothing in storage.
Then whenever you update the stored array you always store back the whole thing into localStorage so that the stored version is always a string replica of the live one.
This way you only use getItem()
once and then have a simple service method storeLocal()
that you call each time you modify array or object in array.
Another thing you might look at is ngStorage that does all of the above for you
Upvotes: 1