[英]AngularJS Shopping Cart implementation - Add / Update items
我正在尝试使用ngCookies使用AngularJS构建购物车服务。
我可以在购物车中成功添加一个项目,但是,如果该项目已经存在于购物车中,我希望addItem
方法增加数量,而不是将新item
推送到items
对象。
如何从addItems
方法获取要添加的项目的index
? 我是要正确解决这个问题还是应该将item索引设置为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);
},
我已经解决了以下问题:我愿意接受更好的建议-
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);
var exists = -1;
angular.forEach(items, function(obj, key) {
if (obj.id == item.id)
{
exists = key;
}
});
// Because array index 0 will be defined as false
if (exists >= -1) {
items[exists].quantity += quantity;
}
else {
items.push({
id : item.id,
quantity : quantity,
price : item.price,
name : item.name,
thumb : item.thumb
});
}
$cookieStore.put(this.itemsCookie, items);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.