【发布时间】:2016-09-03 08:03:40
【问题描述】:
我正在使用 Ionic 框架作为在线课程的一部分,我正在学习 AngularJS 和许多其他对 Web 开发人员有用的工具。而且,作为高级初学者类型,我被卡住了。在本单元中,我们学习了利用本地存储在本地保存数据,这样即使在应用程序关闭后我们也可以获取我们最喜欢的项目。但是,我无法让它发挥作用。
这就是我所做的:
失败的尝试
我可以将数据存入本地存储。我可以附加数据。我使用这个函数来做到这一点:
$scope.favoriteData = $localStorage.getObject('favorites', '[]');
$scope.addFavorite = function (index) {
console.log('Current Favorites', $scope.favoriteData);
$scope.favoriteData = Object.keys($scope.favoriteData).map(function(k) { return $scope.favoriteData[k] });
console.log ($scope.favoriteData);
$scope.storeVar = $scope.favoriteData.push("'{id':" + index + '},');
console.log ($scope.favoriteData);
$localStorage.storeObject('favorites', $scope.favoriteData);
console.log('Added Favorite', $scope.favoriteData)
};
在本地存储中,这会产生以下条目:
favorites: ["'{id':0},","'{id':1},"]
到目前为止一切顺利。然而,这是没有用的。因为我需要这个对象有以下格式:
favorites: [{'id':0}, {'id':1}]
等等。另外,我应该无法添加重复项。我在其他地方有一种功能,但我一直不知道如何结合这两个功能。
我的功能是这样的:
function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({
id: index
});
};
这个问题是,我不明白它是怎么做的。
所以请帮忙?
编辑#1:
第二次尝试
在@Muli 和@It-Z 的帮助下,我现在正在使用以下代码:
$scope.favoriteData = $localStorage.getObject('favorites', '[]');
$scope.addFavorite = function (index) {
console.log('Current Favorites', $scope.favoriteData);
$scope.favoriteData = Object.keys($scope.favoriteData).map(function(k) { return $scope.favoriteData[k] });
console.log ($scope.favoriteData);
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
console.log ("Found duplicate id " + favorites[i].id);
return;
}
}
$scope.storeVar = $scope.favoriteData.push({id: index});
console.log ($scope.favoriteData);
$localStorage.storeObject('favorites', $scope.favoriteData);
console.log('Added Favorite', $scope.favoriteData)
};
但是,这不起作用,因为使用不存在的密钥 favorites,它不起作用并给我一个错误。所以我需要检查密钥是否存在,如果不存在,那么它应该创建一个。我看过this的问题,但没有用,主要是我必须使用services.js中的以下工厂才能访问本地存储:
.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);
}
}
}])
这就是我现在所处的位置。我仍然被困住了。或者再次卡住。我不知道。
【问题讨论】:
标签: javascript arrays angularjs ionic-framework local-storage