[英]How to store array of objects in localStorage?
I have 3 radio buttons say x
, y
and z
. 我有3个单选按钮,分别是
x
, y
和z
。 On click
on x
, data is loaded and so on.. click
x
,将加载数据,依此类推。
Now in localStorage, I want to set data for x
, y
and z
differently and get it. 现在在localStorage中,我想为
x
, y
和z
不同的数据并获取它。
Here, I'm giving a sample of the program. 在这里,我提供了该程序的示例。
Javascript: 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? 如何存储
y
和z
数据,并在切换到单选按钮时应显示在屏幕上?
You should use JSON.stringify
and JSON.parse
. 您应该使用
JSON.stringify
和JSON.parse
。 You have typo on your code and you don't need to set each property. 您的代码上有错别字,不需要设置每个属性。 Just set the
x
on scope. 只需在作用域上设置
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;
}
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. 您应该为此使用
angular.factory
或angular.service
。
In your x-storage.js 在您的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 在你的controller.js中
angular.controller('controllerName', function(xStorage){
$scope.x = xStorage.getX();
$scope.clickButton = function(anyValue) {
xStorage.setX(anyValue);
}
})
You can use setObject(): 您可以使用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
https://www.npmjs.com/package/angular2-cool-storage
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.