0

ショッピングカートを作ろうとしています。後でアクセスできるように、配列請求書を localstorage に追加したいと考えています。

この形式のアプローチにはいくつかのエラーがあると思います

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]);

stringify プロセスは、配列内の不適切な要素 (関数など) を削除することに注意してください。

再解析するには:

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 に答える