Reputation: 548
I am building a mobile application using the Ionic Framework, for my E-Commerce store and I am very new to Ionic. Right now, I am storing the products added to the cart in an array, but this is not efficient as the data will be lost, once the user moves out of the view. Therefore, I need to store the array in local storage.
<a class="item item-thumbnail-left" href="#">
<img ng-src={{product.featured_image.source}}>
<div class="row">
<div class="col">
<h3><span ng-bind="product.ID"></span></h3>
<h3><span ng-bind="product.title"></span></h3>
</div>
</div>
<div class="row">
<div class="col">
<p>{{product.meta_fields.woo.currency_symbol }}<span ng-bind="selectedSize.variation._price" ng-model="productPrice"></span></p>
</div>
</div>
<div class="row">
<div class="col">
<p>Size</p>
<select ng-init="selectedSize = product.meta_fields.woo.variations.items[0]" ng-model="selectedSize" ng-options="size.variation.attribute_pa_size for size in product.meta_fields.woo.variations.items"></select>
</div>
<div class="col">
<p>Qty</p>
<select ng-init="quantity = '1'" ng-model="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
</div>
<div class="col">
<button ng-click="addItem(product.ID, product.title, selectedSize.variation.attribute_pa_size, selectedSize.variation._price, quantity)">Add Me</button>
</div>
</div>
</a>
Controller.js
.factory("items", function () {
var items = {};
items.data = [];
return items;
})
.controller('ItemsController', function($scope,items) {
$scope.items = items;
$scope.addItem = function (id,item,size,price,quantity) {
items.data.push({id,item,size,price,quantity});
localStorage.setItem("cart", JSON.stringify(items));
var cart = localStorage.getItem("cart");
console.log(cart);
}
})
In my Controller.js, I have tried adding the array to Local Storage and output it in the console. The data gets stored in Local Storage and prints it to the console, but the data goes away when reloading the page. I am unable to find out where I'm going wrong.
Upvotes: 1
Views: 4176
Reputation: 827
What gets actually stored in localStorage is a string. Therefore when you read back from localStorage you need to parse the stored string so that you get the original object. In other words, instead of:
var cart = localStorage.getItem("cart");
you need:
var cart = JSON.parse(localStorage.getItem("cart"));
Upvotes: 3