que1326
que1326

Reputation: 2325

How to access values from keys from Local Storage in AngularJs?

I want to access the values from some keys in my Local Storage in the most easiest way with AngularJs. In Resources --> Local Storage I have:

Key:myKey
Value:{ "layouts":[ other_things ],"states":{ other_things  },"storageHash":"fs4df4d51"}

I tried:

console.log($window.localStorage.key(0).valueOf('layouts'));
  //or
console.log($window.localStorage.getItem('myKey'));

RESULT

myKey

Upvotes: 2

Views: 2008

Answers (3)

AlexanderT
AlexanderT

Reputation: 187

From local storage you get JSON data, so you need to parse it to JS object, JSON.parse($window.localStorage.myKey).layouts

Upvotes: 0

jornare
jornare

Reputation: 2893

LocalStorage stores values in strings, not objects. You will need to serialize your object before assigning it and deserialize it when fetching.

var myObject= { "layouts":[ other_things ],"states":{ other_things  },"storageHash":"fs4df4d51"};

// Stringify JSON object before storing
localStorage.setItem('myKey', JSON.stringify(myObject));

// Retrieve the object
var myRetrievedObject = JSON.parse(localStorage.getItem('testObject'));

Upvotes: 0

Tarun Dugar
Tarun Dugar

Reputation: 8971

You can do:

$window.localStorage['myKey']

If the data is of stringified(read: JSON.stringify) then:

angular.fromJson($window.localStorage['myKey']);

Upvotes: 4

Related Questions