ngStorage:使用变量键检索数据

时间:2016-06-10 21:21:26

标签: javascript angularjs local-storage ng-storage

我需要一些帮助...

我需要使用ngStorage angular的插件从localstorage中检索数据......

如果我写

$localStorage.temp = [{ name: "Jhon", lastname: "Pitt"}];
var myVar = $localStorage.temp;

这很好....但如果我写

var str = 'temp';
$localStorage.temp = [{ name: "Jhon", lastname: "Pitt"}];
var myVar = $localStorage.[str]; // this doesn't work
myVar = $localStorage.str; // this doesen't retrieve nothing cause there's no key 'str' in local storage

如果我写这个

var myVar = JSON.parse(window.localStorage.getItem(str));

它有效,但我需要使用$ localStorage 我该如何解决这个问题?我非常需要它......

working plunker

中试用

1 个答案:

答案 0 :(得分:2)

你真的很亲密,但你在$ localStorage上有语法错误。

尝试:

var str = 'temp';
$localStorage.temp = [{ name: "Jhon", lastname: "Pitt"}];
var myVar = $localStorage[str]; // remove the .