如何从AngularJs中的Local Storage访问键中的值?

时间:2015-12-08 10:41:55

标签: javascript angularjs local-storage

我希望以 AngularJs 以最简单的方式访问本地存储中某些键的值。 在资源 - > 本地存储我有:

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

我试过了:

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

RESULT

  

的myKey

3 个答案:

答案 0 :(得分:3)

你可以这样做:

$window.localStorage['myKey']

如果数据是字符串化的(读取:JSON.stringify),那么:

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

答案 1 :(得分:0)

LocalStorage将值存储在字符串中,而不是对象中。在分配对象之前,您需要序列化对象,并在获取时对其进行反序列化。

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'));

答案 2 :(得分:0)

从本地存储中获取JSON数据,因此需要将其解析为JS对象, JSON.parse($ window.localStorage.myKey).layouts

相关问题