简体   繁体   中英

How to store array of objects in localStorage?

I have 3 radio buttons say x , y and z . On click on x , data is loaded and so on..

Now in localStorage, I want to set data for x , y and z differently and get it.

Here, I'm giving a sample of the program.

Javascript:

var setInLocalStorage = function(){
    //on click of  x radio and getting data from model and called 
    // from one  function
    var x = {
        t = model.x.t;
        d = model.x.d;
    }
    localStorage.setItem('x' ,JSON.stringyfy(x));
}

var getFromLocalStorage = function() { 
    var obj = JSON.parse(localStorage.getItem('x'));
    //storing back to model
    model.x.t = obj.t;
    model.x.d = obj.d; 
    // populating data on screen which was stored in local storage
    $scope.x.t = model.x.t ;
    $scope.x.d = model.x.d;
}

How to store data of y and z and should display on screen on switching to radio button?

You should use JSON.stringify and JSON.parse . You have typo on your code and you don't need to set each property. Just set the x on scope.

var setInLocalStorage = function(){
    var x =  model.x
    localStorage.setItem('x', JSON.stringify(x));
}

var getFromLocalStorage = function() { 
    var obj = JSON.parse(localStorage.getItem('x'));
    model.x = obj;
    $scope.x = model.x;
}

But the best practice is not to do these type of actions in your controller. You should be using angular.factory or angular.service for this.

In your x-storage.js

angular.factory('xStorage', function(){
 var x = localStorage.getItem('x') || {};
 return {
  getX: function(){
    return x;
  },
  setX: function(xData){
    x = xData;
    localStorage.setItem('x', xData);
  }
 }
})

In your controller.js

angular.controller('controllerName', function(xStorage){
 $scope.x = xStorage.getX();

 $scope.clickButton = function(anyValue) {
   xStorage.setX(anyValue);
 }
})

You can use setObject():

import { Component, OnInit } from '@angular/core';

import { CoolLocalStorage } from 'angular2-cool-storage';

@Component({
  selector: 'my-app'
})
export class AppComponent implements OnInit { 
    localStorage: CoolLocalStorage;

    constructor(localStorage: CoolLocalStorage) {
        this.localStorage = localStorage;   
    }

    ngOnInit() {
        this.localStorage.setItem('itemKey', 'itemValue');

        console.log(this.localStorage.getItem('itemKey'));

        this.localStorage.setObject('itemKey', {
            someObject: 3
        });

        console.log(this.localStorage.getObject('itemKey'));
    }
}

For More details :

https://www.npmjs.com/package/angular2-cool-storage

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