AngularJS / Javascript为变量语法分配键

时间:2015-07-03 23:58:16

标签: javascript angularjs

由于我在本地存储中放了一个唯一的密钥,我不确定是否必须在视图中引用它

//模型

$localStorage['uniqueKey'] =[{id:1, name:"foo"}, {id:2, name:"bar"}]

//控制器

$scope.users = $localStorage['uniqueKey'];

//查看 - >我必须参考独特的键?或者这没关系??????????

<li ng-repeat="user in users">
{{user.name}}
</li>

1 个答案:

答案 0 :(得分:1)

$scope.users = $localStorage.['uniqueKey']; 
                            ^^ syntax error: dot should not be here

//This should be:

$scope.users = $localStorage['uniqueKey'];
//or
$scope.users = $localStorage.uniqueKey;
//or
$scope.users = $localStorage.get("uniqueKey");

正确使用。在localStorage中存储对象:

$localStorage.uniqueKey = angular.toJson([{id:1, name:"foo"}, {id:2, name:"bar"}]);

$scope.users = angular.fromJson($localStorage.uniqueKey);

您可以使用angular.toJson()将对象转换为字符串,使用angular.fromJson来反转它。的 Demo