Как добавить массив в localstore в angularjs
Я пытаюсь построить корзину. Я хочу добавить фактуру массива в 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 ответа
localStorage["items"] = JSON.stringify(items);
обновление: вы можете получить его следующим образом: `var items:
localStorage.getItem('items');
Локальная сцена сохраняет только строки, а не сложные объекты.
Таким образом, вы можете преобразовать его при сохранении и повторно проанализировать при доступе к нему.
localStorage['foo'] = JSON.stringify([1, 2, 3]);
Имейте в виду, что процесс stringify удалит все неподходящие элементы в массиве, например, функции.
Чтобы пересмотреть это:
var arr = JSON.parse(localStorage['foo']);
localStorage поддерживает только строки, поэтому для работы через localStorage необходимо использовать JSON.stringify() и JSON.parse().
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"));
localStorage
поддерживает только строки, поэтому вы должны использовать следующий код:
var p = [];
p[0] = "some";
localStorage["p"] = JSON.stringify(p);