我试图将此对象保存到$window.localStorage()
:
CTRL:
app.controller('ctrl', function($window, $scope) {
$scope.initData = [
{
customer: 1,
firstName: "John",
lastName: "Doe"
},
{
customer: 2,
firstName: "Jane",
lastName: "Doe"
},
{
customerId: 3,
firstName: "John",
lastName: "Smith",
}
];
// scopes
for(var i = 0; i < $scope.initData.length; ++i) {
$window.localStorage.setItem(i, JSON.stringify($scope.initData[i]));
}
});
但是我用键作为索引来获取值。我也试过这个:
for(var i = 0; i < $scope.initData.length; ++i) {
$window.localStorage.setItem(i, Object.values($scope.initData[i]));
}
和for..in
,但无法找出最佳方式。
现在,当我console.log(localStorage);
时,我将其作为输出:
0:"{"customer":1,"firstName":"John","lastName":"Doe"}"
1:"{"customer":2,"firstName":"Jane","lastName":"Doe"}"
2:"{"customer":3,"firstName":"John","lastName":"Smith"}"
当我访问0
作为键时,我将customer
作为值,我需要将1
作为值。 customer
应该是关键。
我怎样才能做到这一点?我该怎么转换呢?
答案 0 :(得分:1)
只需将对象$scope.initData
完整地保存到localStorage
,我就看不到单独保存initData
个对象的好处。在应用程序加载时从localStorage
加载客户,并将其保存在更新中。但是不能直接使用localStorage
- 我会使用service
。
// Set localStorage item
localStorage.setItem('initData', JSON.stringify(dataObject));
// Retrieve the object from localStorage
var retrievedObject = localStorage.getItem('initData');
// console.log retrieved item
console.log('retrieved data Object: ', JSON.parse(retrievedObject));
或者您可以将您的密钥更改为此内容(将客户唯一ID作为参考),而不是您的循环计数器:
for(var i = 0; i < $scope.initData.length; ++i) {
$window.localStorage.setItem('customer-id' + $scope.initData[i].customer, JSON.stringify($scope.initData[i]));
}
});