Reputation: 15
I am creating a shopping application(Angular JS and Ionic). Whenever I add an item to the cart it gets overwrites the previous element. Below is my code:
detail.html:
<ion-view view-title="DetailPage">
<ion-content>
<h4>
Product Details
</h4>
<ion-view view-title="playlists">
<ion-content>
<input type="button" ng-click="addToCart();" value="add cart" />
</ion-content>
</ion-view>
Controller.js:
.controller('detailsCtrl', function($scope, $stateParams) {
var productname = $stateParams.playlistname;
var arr = [];
$scope.addToCart = function() {
arr.push(productname);
localStorage.setItem('arr', arr);
})
How do I handle the overwriting of elements?
Upvotes: 1
Views: 295
Reputation: 12431
You're reinitialising the array each time and then writing the new array to local storage. You need to retrieve the existing array from local storage and then push elements on to it:
.controller('detailsCtrl', function($scope, $stateParams) {
var productname = $stateParams.playlistname;
// Get the product array from local storage if it exists
// or initialise a new array.
var arr = localStorage.getItem('arr') || [];
$scope.addToCart = function() {
arr.push(productname);
localStorage.setItem('arr', arr);
})
Upvotes: 2