繁体   English   中英

如何在AngularJS应用程序中将数据数组保存到本地存储?

[英]How to save an array of data to local storage in an AngularJS app?

我正在尝试在iOS上创建angularJS应用,我想将复选框上的数据保存到本地存储中。

现在我有了复选框的信息数组

$scope.cuisineList = [
    { text: "Asian Cuisine", checked: true },
    { text: "Cafe", checked: true },
    { text: "Chinese Cuisine", checked: true },
    { text: "Dessert and Bekery", checked: true },
    { text: "Dim Sum", checked: false },
    { text: "Ice Cream", checked: false },
    { text: "Japanese Cuisine", checked: false },
    { text: "Kiwi Cuisine", checked: false },
    { text: "Korean Cruisine", checked: false },
    { text: "Thai Cuisine", checked: false },
    { text: "Vegeterian Cuisine", checked: false }
];

和我的html5(我使用图标框架)

<ion-checkbox ng-repeat="item in cuisineList"
                  ng-model="item.checked" 
                  ng-checked="item.checked"
                  ng-change="cuisineListChange()">
            {{ item.text }}
        </ion-checkbox>

当复选框发生更改时,它将执行cuisineListChange()函数,我想将$scope.cuisineList保存到其中。

请给我一个例子,如何使用本地存储来保存复选框。

谢谢。

由于您无法将对象存储在localStorage或sessionStorage中,因此需要对它们进行序列化(这样,一个字符串将被保存到localStorage中,返回时需要对其进行解析)。

要存储,请使用:

localStorage.setItem('cuisineList', JSON.stringify($scope.cuisineList));

要从localStorage取回数据,请使用:

$scope.cuisineList = JSON.parse(localStorage.getItem('cuisineList'));

这是一个有用的对象:

var LocalStorageManager = {
    setValue: function(key, value) {
        window.localStorage.setItem(key, JSON.stringify(value));
    },
    getValue: function(key) {
        try {
            return JSON.parse(window.localStorage.getItem(key));
        } catch (e) {

        }
    }
};

要保存数据:

LocalStorageManager.setValue("key",data);

要检索该数据:

LocalStorageManager.getValue("key");

暂无
暂无

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

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