我有3个单选按钮说x
,y
和z
。在click
x
上,数据已加载,依此类推......
现在在localStorage中,我想以不同的方式设置x
,y
和z
的数据并获取它。
在这里,我提供了该计划的样本。
使用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;
}
如何存储y
和z
的数据,并在切换到单选按钮时显示在屏幕上?
答案 0 :(得分:5)
您应该使用JSON.stringify
和JSON.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.factory
或angular.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'));
}
}
更多详情: