嗨,伙计们,我想用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;
}])问题是,当我添加一个最喜欢的项时,它会在数组中替换自己,而不是向数组中添加一个新项,
我真的很感谢你的帮助
发布于 2016-06-19 19:56:04
你在存储时做错了。您要用单个项替换数组。还要注意的是,Array.prototype.push()返回集合的长度。
enter code herefavFac.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);
//favorites.push({id: index});
};发布于 2016-06-19 19:59:09
您只需更改addToFavorites方法,如
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);
};现在,它将首先添加一个项,然后将数组保存到本地存储中。
发布于 2016-06-23 00:36:47
作为建议,我建议您使用ngStorage,它使您可以将项作为一个简单命令从localStorage中添加或删除:
$localStorage.favorites = [];就这样了,现在您在localStorage中有了收藏夹列表,每当您修改这个数组时,都会在localStorage上直接获得结果。
$localStorage.favorites.push(newItemToAdd); // this adds a item.
$localStorage.favorites = $localStorage.favorites
.filter((v, i) => i !== indexOfItemToDelete); // removes item.https://stackoverflow.com/questions/37911219
复制相似问题