AngularJS在Cookie中存储对象数组 [英] AngularJS storing array of objects in a cookie
问题描述
我在scope变量中存储了一个对象数组.问题在于,当用户刷新页面时,它不会保留该数据,因此我正在考虑使用Cookie.
I have an array of objects stored in the scope variable. The issue with that is when the user refreshes the page, it does not persist that data, so I am considering using cookies.
变量$ scope.Users存储一个用户对象数组,我正在使用以下代码将这些数据存储到cookie中:
The variable $scope.Users stores an array of user objects and I am using the following code to get that data into a cookie:
if ($cookies.getObject('user_data') === '' || $cookies.getObject('user_data') === undefined)
$cookies.putObject('user_data',$scope.Users);
我没有使用任何数据
console.log($ cookies.getObject('user_data'))
console.log($cookies.getObject('user_data'))
,我什么也没回来,所以putObject似乎不保存数据.这有什么问题吗?Cookie的大小可以超过限制吗?
and I am not getting anything back, so it seems that putObject does not save the data. What could be wrong here? Could the size of the cookie exceed the limit?
以前,我使用以下方法从html页面中检索数据:
Previously I used the following to retrieve that data from my html page:
<tr ng-repeat="User in Users">
<td>{{User.Name}}</td>
<td>{{User.ID}}</td>
<td>{{User.DOB}}</td>
<td>{{User.Status}}</td>
</tr>
我的问题是如何从Cookie中检索数组并显示其内容?还有没有更好的方法可以通过刷新来持久化对象数组?服务会更好吗?
My question is how to I retrieve the array from cookies and display its contents? Also is there a better way to persist an array of objects through refresh? Would service work better?
推荐答案
您可以尝试以下代码.
var obj = {"Name": name, "ID": id, "DOB": dob, "Status": status};
$scope.Users.push(obj);
$cookies.put('user_data', JSON.stringify($scope.Users));
var s = $cookies.get('user_data');
$scope.Users= JSON.parse(s);
这篇关于AngularJS在Cookie中存储对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!