0

我正在尝试构建一个购物车。我想将数组发票添加到本地存储,以便以后可以访问它。

我想这种方法有一些错误

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 包含一个按钮,它将新项目推送到自动绑定的数组中。

<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>
4

4 回答 4

1

本地阶段只保存字符串,不保存复杂对象。

因此,您可以做的是在保存时对其进行字符串化,并在访问时对其进行重新解析。

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

请注意,字符串化过程将删除数组中任何不合适的元素,例如函数。

要重新解析它:

var arr = JSON.parse(localStorage['foo']);
于 2014-03-17T11:21:44.623 回答
0
localStorage["items"] = JSON.stringify(items);

更新:您可以按如下方式检索它:`var items:

localStorage.getItem('items');

资源

于 2014-03-17T11:20:55.903 回答
0

localStorage 仅支持字符串,因此您必须使用 JSON.stringify() 和 JSON.parse() 才能通过 localStorage 工作。

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

对于您的代码:

var items = [{
        qty: 10,
        description: 'item',
        cost: 9.95}];
localStorage.setItem("items", JSON.stringify(items));
// get 
var items = JSON.parse(localStorage.getItem("items"));
于 2014-03-17T11:21:29.380 回答
0

localStorage仅支持字符串,因此您必须使用以下代码:

var p = [];
p[0] = "some";
localStorage["p"] = JSON.stringify(p);
于 2014-03-18T05:14:14.763 回答