ngStorage:使用可变键检索数据

ngStorage: retrive data with variable key

我需要一些帮助...

我需要使用 ngStorage angular 的插件从本地存储中检索数据...

如果我写

$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

中试试

你真的很接近,但你在 $localStorage 上有一个语法错误。

尝试:

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