努力添加购物车本地存储逻辑

时间:2016-04-08 16:20:43

标签: javascript angularjs

   $scope.toCart = function(id,item){

      var toSaveArray = [];
      var toSaveObj = {
        id: item._id,
        name : item.name,
        image : item.image[0],
        price : item.price,
        discount_price : item.discount_price,
        qty : 1
      }

      toSaveArray.push(toSaveObj);

      var fromSaved = JSON.parse(localStorage.getItem('cart'));

      if(fromSaved){
          for(i=0;i<fromSaved.length;i++){
          if(fromSaved[i].id == id){
            fromSaved[i].qty += 1;
            toSaveArray.push(fromSaved);
          }
        }
      }

      localStorage.setItem('cart',JSON.stringify(toSaveArray));

   }

如果项目存在,请添加一个数量,否则只需将对象添加到数组中。但是由于这个简单的逻辑,我没有一个有效的代码。上面的代码已经破了。

2 个答案:

答案 0 :(得分:2)

我解决了一些逻辑错误:

$scope.toCart = function(id, item) {
    var cart = JSON.parse(localStorage.getItem('cart'));
    if (!cart) {
        cart = [];
    }

    var index = cart.findIndex(function (cartItem) {
        return cartItem.id === item._id;
    });

    if (index !== -1) {
        cart[index].qty += 1;
    } else {
        cart.push({
            id: item._id,
            name : item.name,
            image : item.image[0],
            price : item.price,
            discount_price : item.discount_price,
            qty : 1
        });
    }

    localStorage.setItem('cart',JSON.stringify(cart));

}

答案 1 :(得分:0)

您的代码在这些步骤上做错了:

  • 比较之前的item._id与参数id
  • 始终保存item参数
  • 执行不必要的
    $scope.toCart = function(item){
    
        var toSaveArray = [];
        var toSaveObj = {
            id: item._id,
            name : item.name,
            image : item.image[0],
            price : item.price,
            discount_price : item.discount_price,
            qty : 1
        };
    
        var fromSaved = JSON.parse(localStorage.getItem('cart'));
    
        if(fromSaved){
            var savedItem = $filter('filter')(fromSaved, {id: item._id});
            if (savedItem) {
                fromSaved[fromSaved.indexOf(savedItem[0])].qty++;
            }
    
            toSaveArray = fromSaved;
        } else {
            toSaveArray.push(toSaveObj);
        }
    
        localStorage.setItem('cart',JSON.stringify(toSaveArray));
    };
    

以上代码应涵盖所有内容。