将对象数组保存到本地存储不工作
Saving Object Array to local storage not working
你好,我试图创建一个简单的客户端购物车,在我的控制器中,当页面加载时,我定义了数组对象,将持有我的项目,如果它们是未定义的或有0的长度,我设置它们默认为'[]':
$scope.cart = JSON.parse($window.localStorage.getItem('cart')) || [];
$scope.cart.items = $scope.cart.items || [];
这是将商品添加到购物车中的函数:
$scope.addItem = function(item) {
if (item.quantity > 0)
{
var cartItem = {
id: item.id,
description: item.class + ' item' + (item.quantity > 1 ? 's' : '') + ' to ' + $scope.details.name,
quantity: item.quantity
}
// Adding item to cart array
$scope.cart.items.push(cartItem)
// Saving cart to storage
$window.localStorage.setItem('cart', JSON.stringify($scope.cart));
// Checking to see if data has indeed been stored in localstorage
console.log(JSON.parse($window.localStorage.getItem('cart')));
}
}
现在我的购物车在存储总是显示为空,有几次我玩了代码,让它工作(不知道我做了什么),但当我重新加载页面时,一切都被清除。
您将cart
初始化为数组,但随后为其分配属性。
应该是一个对象:
$scope.cart = JSON.parse($window.localStorage.getItem('cart')) || {};
同样,在您可以将push
转换为cart
中的数组之前,需要定义该数组。
最简单的可能是首先在一个对象中提供所有属性:
var newCart = {
tickets:[],
items:[]
}
$scope.cart = JSON.parse($window.localStorage.getItem('cart')) || newCart ;
您应该检查是否已经有一个值存储为
if(!$window.localStorage.getItem('cart'))
{
// Saving cart to storage
$window.localStorage.setItem('cart', JSON.stringify($scope.cart));
}
相关文章:
- 将函数引用存储在散列中在javascript中无法正常工作
- 存储创建工作,存储定义不工作
- 本地存储在使用 js 和 html5 的游戏中无法正常工作
- 本地存储未按预期工作
- 是否有跨子域工作的现代会话存储替代方案
- 本地存储未按预期工作
- 与“click”事件一起存储的jQuery元素未按要求工作
- 使用 ajax 将文本区域信息存储到数据库中.除非我以任何方式编辑文本区域,否则工作正常.信息仍然被存储,但XMLHTT
- 本地存储在火狐中无法按预期工作.返回空值的对象
- 临时存储无法在拉拉维尔工作
- Chrome本地存储;t在Mac OS中工作属性
- HTML5存储不工作
- html5本地存储没有按我想要的方式工作
- 本地存储无法与for循环一起工作
- 我可以在浏览器ui线程和web工作线程中安全地使用html5中的哪些本地存储
- HTML5本地存储功能在我的IOS Phonegap应用程序中突然停止工作
- Chrome应用程序本地存储不持久,Chrome.storage不工作
- Windows Phone 8.1本地存储无法工作
- 本地存储中的数组和对象不工作
- 会话存储工作不正常