javascriptangularjslocal-storageng-storage

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


Solution

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

    Try:

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