简体   繁体   English

AngularJS:无法将localStorage项保存到作用域变量中

[英]AngularJS: unable to save the localStorage item into scope variable

I'm using window.localStorage.getItem('job_id.done_tasks') to store the values into $scope level variable. 我正在使用window.localStorage.getItem('job_id.done_tasks')将值存储到$scope级别变量中。 I'm failing to do so. 我没有这样做。 Please check my code. 请检查我的代码。

$scope.done_tasks = {};
$scope.done_tasks = window.localStorage.getItem('job_id.done_tasks');

when i alert('$scope.done_tasks'); 当我alert('$scope.done_tasks'); it says undefined but when i use this alert(window.localStorage.getItem('job_id.done_tasks')); 它说undefined但是当我使用此alert(window.localStorage.getItem('job_id.done_tasks')); it shows 16,17 . 它显示16,17 Why i am unable to store the values of window.localStorage.getItem('job_id.done_tasks') to $scope.done_tasks . 为什么我无法将window.localStorage.getItem('job_id.done_tasks')的值存储到$scope.done_tasks Help me out regarding this. 帮我解决这个问题。

Please check below code, local storage returns string as an output , you need to parse it to object. 请检查以下代码,本地存储将字符串作为输出返回,您需要将其解析为对象。

$scope.done_tasks = JSON.parse(window.localStorage.getItem('job_id.done_tasks'));

For your ref: 供您参考:

window.localStorage.setItem(key,value);
window.localStorage.getItem(key);

That's how local storage works, whatever key you have provided to save value, the same key you have to use to fetch data. 这就是本地存储的工作方式,无论您提供了什么用于保存价值的密钥,都必须使用与获取数据相同的密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM