Angularjs - 如何在数组和本地存储中存储对象

时间:2016-02-27 19:46:35

标签: angularjs ionic-framework

如何将多个对象存储到一个数组中,然后存储到本地存储中,这样我就可以在需要时使用循环获取所有对象。

示例对象:

var newMsg = {
      sentDate: msgDate,
      sentTime: msgTime,
      msgTitle: "message title",
      msgDesc: "message desc"
    };

目前我正在使用https://github.com/grevory/angular-local-storage#configuration-example angularjs模块,但很难从数组中存储和检索对象。

我尝试过以下代码:

msgArray = [];
var savedMsgs = localStorageService.set("wimmtkey", newMsg);

    msgArray.push(savedMsgs); 
    console.log(savedMsgs);

这在控制台中输出'true'但期望看到存储的对象。还请建议循环访问数组以检索对象。谢谢。

1 个答案:

答案 0 :(得分:5)

更多代码会有用,但对于angular-local-storage,这是在将对象保存到localStorage之前将对象推送到数组中的方式:

var msgArray = [];
var newMsg = {
    sentDate: msgDate,
    sentTime: msgTime,
    msgTitle: "message title",
    msgDesc: "message desc"
};

//you can push all the objects here before saving to the storage
//maybe you have a forEach here, pushing the objects? Who knows
msgArray.push(newMsg); 

//the array is now set in the storage
localStorageService.set("wimmtkey", msgArray); 

//the array obtained from local storage
var obtained_array = localStorageService.get("wimmtkey");