2016-02-27 182 views
6

如何將多個對象存儲到數組中然後存儲到本地存儲中,以便在需要時使用循環可以獲取所有對象。Angularjs - 如何將對象存儲在數組和本地存儲中

例如對象:

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); 

這輸出在控制檯「真」,但期待看到存儲的對象。另請建議循環訪問數組以檢索對象。謝謝。

+0

,則使用set方法在localStorage中設置數組。 當你想獲得數組時,你將不得不使用get方法 – Akis

回答

4

一些更多的代碼將是有用的,但對於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"); 
一般
+2

你不需要使用這個庫進行字符串化,因爲'set'函數在引擎蓋下利用了angular的'toJson()'方法。同樣,'get'方法'JSON.parse()'是要返回的項目。不需要那個。 –

+0

感謝您的閱讀,編輯答案 – Akis

+0

謝謝,按預期工作。 – GreenDome