Search code examples
javascripthtmlangularjscookiestore

how to add an array to localstore in angularjs


I am trying to build a shopping cart. I want to add the array invoice to localstorage so that i could access it later.

I guess there are some errors with this form of approach

angular.module('myApp', ['ngCookies']);
function CartForm($scope, $cookieStore) {
$scope.invoice.items = $cookieStore.get('items');
$scope.addItem = function() {
    $scope.invoice.items.push({
        qty: 1,
        description: '',
        cost: 0
    });
   $scope.invoice.items = $cookieStore.put('items');
},

$scope.removeItem = function(index) {
    $scope.invoice.items.splice(index, 1);
 $scope.invoice.items = $cookieStore.put('items');
},

$scope.total = function() {
    var total = 0;
    angular.forEach($scope.invoice.items, function(item) {
        total += item.qty * item.cost;
    })

    return total;
 }
 }

HTML contains a button , which pushes the new items to the array which gets automatically binded.

<div ng:controller="CartForm">
<table class="table">
    <tr>

        <th>Description</th>
        <th>Qty</th>
        <th>Cost</th>
        <th>Total</th>
        <th></th>
    </tr>
    <tr ng:repeat="item in invoice.items">
        <td><input type="text" ng:model="item.description"class="input-small"></td>           
        <td><input type="number" ng:model="item.qty" ng:required class="input-mini">  </td>
        <td><input type="number" ng:model="item.cost" ng:required class="input-mini">  </td>
        <td>{{item.qty * item.cost | currency}}</td>
        <td>
            [<a href ng:click="removeItem($index)">X</a>]
        </td>
    </tr>
    <tr>
        <td><a href ng:click="addItem()" class="btn btn-small">add item</a></td>
        <td></td>
        <td>Total:</td>
        <td>{{total() | currency}}</td>
    </tr>
</table>
</div>

Solution

  • localStorage["items"] = JSON.stringify(items);
    

    update: you can retrieve it as follows: `var items:

    localStorage.getItem('items');
    

    source