Antonio Kida Antonio Kida - 5 months ago 53
AngularJS Question

Angular LocalStorage

Hi guys i am trying to save some information with localStorage in angular, i injected $window to my service and i created a factory call $localStorage

.factory('$localStorage', ['$window', function($window) {
return {
store: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key,defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
}
}])


i have other factory where i make us of the localStorage factory in order to save some favorites

factory("favoriteFactory", ["$resource", "baseURL", "$localStorage", function($resource, baseURL, $localStorage) {
var favFac = {};
var favorites = $localStorage.getObject("favorites", "[]");

favFac.addToFavorites = function(index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}

$localStorage.storeObject("favorites", {id: index});
//favorites.push({id: index});
};

favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
}
}
}

favFac.getFavorites = function () {
return favorites;
};

return favFac;
}])


the problem is when i add a favorite item, it replaces itself in my array, instead of adding a new one to the array,

i really aprecciate the help
thanks in advance

Answer

You just need to change addToFavorites method like

favFac.addToFavorites = function(index) {
            for (var i = 0; i < favorites.length; i++) {
                if (favorites[i].id == index)
                    return;
            }

            favorites.push({id: index});
            $localStorage.storeObject("favorites", favorites);

        };

Now it will add an item first then save your array into the local storage.

Comments