shall shall - 2 years ago 85
Javascript Question

ngStorage: retrive data with variable key

I need some help...

I need to retrieve data from localstorage with ngStorage angular's plugin...

If I write

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

this is fine.... but If I write

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

If I write this

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

It works, but I need to use $localStorage
How can I solve the problem? I need it so much...

Try it in my working plunker

Answer Source

You were really close, but you had a syntax error on $localStorage.


var str = 'temp';
$localStorage.temp = [{ name: "Jhon", lastname: "Pitt"}];
var myVar = $localStorage[str]; // remove the .
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download