将Object Literal保存到AngularJS中的localStorage

时间:2017-06-14 09:02:03

标签: javascript jquery html angularjs local-storage

我试图将此对象保存到$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应该是关键。

我怎样才能做到这一点?我该怎么转换呢?

1 个答案:

答案 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]));
        }
});