简体   繁体   中英

Saving Object Literal to localStorage in AngularJS

I'm trying to save this object into $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]));
        }
});

But I get the values with keys as indexes.. I've also tried this:

for(var i = 0; i < $scope.initData.length; ++i) {
           $window.localStorage.setItem(i, Object.values($scope.initData[i]));
        }

and with for..in , but couldn't figure out what would be the best way.

Now, when I do console.log(localStorage); I have this as output:

0:"{"customer":1,"firstName":"John","lastName":"Doe"}"
1:"{"customer":2,"firstName":"Jane","lastName":"Doe"}"
2:"{"customer":3,"firstName":"John","lastName":"Smith"}"

When I access the 0 as key, I get customer as value, and I need to get 1 as value. customer should be the key.

How can I achieve this? How can I convert this?

Just save the object $scope.initData completly to the localStorage , I don't see advantage of saving the initData objects seperatly. Load the customers from localStorage on application load, and save them on update. But don't work from the localStorage directly - I would use a service on top of that.

// 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));

Or you could change your key to something as this (taking the customer unique ID as reference), and not your loop counter :

for(var i = 0; i < $scope.initData.length; ++i) {
           $window.localStorage.setItem('customer-id' + $scope.initData[i].customer, JSON.stringify($scope.initData[i]));
        }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM