2016-04-08 24 views
0
$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)); 

    } 

如果項目存在,添加一個qty,否則只是將該對象添加到數組中。但是用這個簡單的邏輯,我沒有一個工作代碼。以上代碼已損壞。努力與添加到購物車本地存儲邏輯

+1

'上面的代碼broken'怎麼會這樣?它在做什麼? –

+0

具體是什麼被打破? –

+1

我認爲你的邏輯回到'toSaveArray.push(fromSaved);'從我所看到的,將'toSaveObj'推到現有的save('fromSaved')將會更有意義,然後重新保存。 – DBS

回答

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

@ cody-jonas解決它,謝謝 –

+0

這實際上是一個非常聰明的解決方案! –

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)); 
    }; 
    

上面的代碼應該涵蓋所有這些。