【发布时间】:2014-08-18 11:52:03
【问题描述】:
我正在尝试使用 ngCookies 使用 AngularJS 构建购物车服务。
我可以成功地将商品添加到购物车中,但是如果商品已经存在于购物车中,我希望 addItem 方法增加数量,而不是将新的 item 推送到 items 对象。
如何从addItems 方法中获取正在添加的项目的index?我是否正确地解决了这个问题,还是应该将项目索引设置为 item.id 来解决这个问题?
app.factory('CartService', ['$cookieStore', function($cookieStore) {
var cart = {
itemsCookie : '',
init : function (itemsCookie) {
this.itemsCookie = itemsCookie;
},
getAll : function () {
var items = $cookieStore.get(this.itemsCookie);
return items;
},
addItem : function(item, quantity) {
// If cookie not defined, then put an empty array
if (! ($cookieStore.get(this.itemsCookie) instanceof Array)) {
$cookieStore.put(this.itemsCookie, []);
}
if (quantity === undefined) {
quantity = 1;
}
var items = $cookieStore.get(this.itemsCookie);
items.push({
id : item.id,
quantity : quantity,
price : item.price,
name : item.name,
thumb : item.thumb
});
$cookieStore.put(this.itemsCookie, items);
},
getItemByIndex : function(index) {
var items = $cookieStore.get(this.itemsCookie);
return items[index];
},
updateQuantity : function(index, quantity) {
var items = $cookieStore.get(this.itemsCookie);
items[index].quantity = quantity;
$cookieStore.put(this.itemsCookie, items);
},
【问题讨论】:
标签: javascript angularjs session-cookies shopping-cart