如何在localStorage中存储对象数组?

时间:2017-08-01 05:46:22

标签: javascript angularjs

我有3个单选按钮说xyz。在click x上,数据已加载,依此类推......

现在在localStorage中,我想以不同的方式设置xyz的数据并获取它。

在这里,我提供了该计划的样本。

使用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;
}

如何存储yz的数据,并在切换到单选按钮时显示在屏幕上?

2 个答案:

答案 0 :(得分:5)

您应该使用JSON.stringifyJSON.parse。您的代码输入错误,并且您不需要设置每个属性。只需在范围内设置x

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;
}

但最佳做法是不在控制器中执行这些类型的操作。您应该使用angular.factoryangular.service

在你的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);
  }
 }
})

在你的controller.js

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

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

答案 1 :(得分:1)

您可以使用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'));
    }
}

更多详情:

  

Hystrix