大家好,我正在尝试使用 localStorage 以角度保存一些信息,我将 $window 注入我的服务并创建了一个工厂调用 $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);
}
}
}])
我有其他工厂,我让我们使用 localStorage 工厂,以保存一些收藏夹
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;
}])
问题是当我添加一个最喜欢的项目时,它会在我的数组中替换自己,而不是在数组中添加一个新的,
我真的很感谢您的帮助