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>
有帮助吗?

解决方案 2

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

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

localStorage.getItem('items');

source

其他提示

Local stage saves only strings, not complex objects.

What you can do, therefore, is stringify it when saving and re-parse it when accessing it.

localStorage['foo'] = JSON.stringify([1, 2, 3]);

Be aware that the stringify process will strip out any unsuitable elements in the array, e.g. functions.

To re-parse it:

var arr = JSON.parse(localStorage['foo']);

localStorage supports only strings, so that why you must use JSON.stringify() and JSON.parse() to work via localStorage.

var p = [];
p[0] = "some";
localStorage["p"] = JSON.stringify(p);

For your code:

var items = [{
        qty: 10,
        description: 'item',
        cost: 9.95}];
localStorage.setItem("items", JSON.stringify(items));
// get 
var items = JSON.parse(localStorage.getItem("items"));

localStorage supports only strings, so you must use the following code:

var p = [];
p[0] = "some";
localStorage["p"] = JSON.stringify(p);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top