2016-07-26 49 views
2

我看了一些例子,但似乎無法弄清楚這一點。基本上,我在離子應用程序中有一個聯繫表單,允許用戶聯繫列表所有者。localStorage使用角度獲取值

當他們提交表單時,我想將廣告ID存儲在本地存儲中,這樣他們就無法一次又一次地將其重複提交。

我需要能夠存儲json數組,然後檢查結果。如果廣告ID在會話存儲中不顯示錶單,則顯示它。

我目前正在這樣做,它似乎將ad id存儲在一個數組中,但是如何循環檢查id是否存在?我嘗試了每個角度,但結果來作爲一個對象。

// Parse any JSON previously stored in allEntries 
    var existingEntries = JSON.parse(localStorage.getItem("store_owner_ad_contacts")); 
    if(existingEntries == null) existingEntries = []; 

    var adId = { 
    "id":$scope.adId 
    }; 
    // Save allEntries back to local storage 
    existingEntries.push(adId); 
    localStorage.setItem("store_owner_ad_contacts", JSON.stringify(existingEntries)); 

    var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts")); 
    angular.forEach(values, function(value, key) { 

    //^This is coming as an object how can I get the key value? 

    if(value == adId){ 
    //form has been submitted before 
    }else{ 
    // showformVar = true 

    console.log(key + ': ' + value); 
    }); 

我的存儲看起來像這樣

 [{"id":"100033"},{"id":"100035"},{"id":"1000336"}] 

我如何獲得的值id? (例如1000033)

+0

你是什麼當你做'var values = JSON.parse(localStorage.getItem(「store_owner_ad_contacts」));'你可以在這裏發佈嗎? –

+0

更新了我的問題。我得到 - [{「id」:「100033」},{「id」:「100035」},{「id」:「1000336」}]如何獲得id值? (例如1000033) – limit

+0

如果你不喜歡'angular.forEach',那麼你可以使用簡單的javascript for循環,如@ Sasank的回答 –

回答

2

在你的循環,你有一個對象,因此只需獲得id屬性像你這樣一個對象:object.yourProperty或對象[yourProperty]

var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts")); 

    values.forEach(values, function(item, i) { 

    // you get object like this {id: "100033"} 
    // so to access id do like normal object 

    if (item.id === '100033') { 
     // do something 
    } 

    }); 
+0

謝謝,這工作。 – limit

1
// inside forEach loop 
var k = 0; 
for(k in value) { 
    // u can get the key in this way (k) 
} 
+0

謝謝。我的存儲看起來像這樣[{「id」:「100033」},{「id」:「100035」},{「id」:「1000336」}] 如何獲取id值? (例如1000033)這是我卡住的地方。 – limit

+0

@limit'JSON.parse(localStorage.get(yourKey))[0] .id' – choz

+0

儘管這段代碼可以解決這個問題,[包括解釋](// meta.stackexchange.com/questions/114762/explaining - 完全基於代碼的答案)確實有助於提高發布的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ

1

正如我所看到的,這不是關於角度本身(使用角度並不意味着關係)。如果你有一組數值並想要搜索某些東西,那麼你可以使用Array.prototype.find。 如果你的數據是字符串數組,那麼你應該先用JSON.parse解析它。

如果您要在角度應用程序中使用localStorage,那麼最好使用ngStorage,它可以處理字符串化和解析以及其他一些選項。

var lsItems = [{"id":"100033"},{"id":"100035"},{"id":"1000336"}]; 
 

 
var item = lsItems.find(i => i.id === "100035"); 
 
console.log(item)