簡體   English   中英

AngularJS購物車實施-添加/更新項目

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM