我正面临在AngularJS中存储到本地存储的问题。我正在使用Ionic Framework开发电子商务移动应用程序并使用ng-repeat显示产品数据。每个离子项都有产品详细信息和一个与TodoController中的addItem()相关联的按钮。单击该按钮,产品数据将存储到本地存储中。但是,问题在于,每当我点击一系列按钮时,只有按下该按钮的最后一个产品才会存储在本地存储中,并且之前点击的按钮的数据不会。
<a class="item item-thumbnail-left" href="#">
<img ng-src={{product.featured_image.source}}>
<div class="row">
<div class="col">
<h3><span ng-bind="product.ID"></span></h3>
<h3><span ng-bind="product.title"></span></h3>
</div>
</div>
<div class="row">
<div class="col">
<p>{{product.meta_fields.woo.currency_symbol}}{{product.meta_fields.woo.price}}</p>
</div>
</div>
<div class="row">
<div class="col">
<p>Qty</p>
<select ng-init="quantity = '1'" ng-model="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
</div>
<div class="col"></div>
<div class="col" ng-controller="TodoController">
<button ng-click="addItem(product.ID, product.title,none , product.meta_fields.woo.price, quantity)">Add Me</button>
</div>
</div>
</a>
控制器
.controller('TodoController', function($scope) {
$scope.saved = localStorage.getItem('todos');
$scope.todos = (localStorage.getItem('todos')!==null) ? JSON.parse($scope.saved) : [];
localStorage.setItem('todos', JSON.stringify($scope.todos));
$scope.addItem = function (id,item,size,price,quantity) {
$scope.todos.push({id,item,size,price,quantity});
localStorage.setItem('todos', JSON.stringify($scope.todos));
}
})
答案 0 :(得分:0)
问题出在您的控制器中,您只传递没有键的对象中的值。你需要修改$ scope.addItem函数
$scope.addItem = function(id, item, size, price, quantity) {
$scope.todos.push({
id: id,
item: item,
size: size,
price: price,
quantity: quantity
});
localStorage.setItem('todos', JSON.stringify($scope.todos));
}
此外,我为您创建了一个plunker示例,请查看http://plnkr.co/edit/3Uzj0Zz9TVYftjFyEGv4?p=preview
答案 1 :(得分:0)
确保您没有字符串&#39; undefined&#39;或者在localStorage中未定义:
$scope.todos = (localStorage.getItem('todos')!==null &&
localStorage.getItem('todos')!=='undefined') ? JSON.parse($scope.saved) : [];