2016-05-29 73 views
0

我想添加新項目到$ localStorage加上舊項目。但是,在我的代碼$ localStorage放棄所有以前的項目。我的代碼如下,

 $scope.cart = []; 
 

 
     $scope.cart = productService.getSharedProduct();   
 

 
     if ($scope.cart != 0) { 
 
      
 
      $localStorage.items = $scope.cart; 
 
     } 
 

 
     else { 
 
      $scope.cart = $localStorage.items; 
 
     }

回答

1

是因爲你沒有將項目添加到您的$localStorage.items但你把它每次分配新的價值觀,因此它失去了最後的附加價值。 您每次都重新初始化它們,因此它們會丟失最後添加的值。

你應該做這樣的事情

if ($scope.cart != 0) { 

    // instead of this    
    //$localStorage.items = $scope.cart; 

    // you should do this 
    for(var i=0; i<$scope.cart.length; i++) 
    { 
     $localStorage.items.push($scope.cart[i]); 
    } 
} 
+0

它的工作原理,非常感謝@Pawan – Rubel

+0

歡迎您!如果它對你有用(請點擊我的答案中的複選標記),請將答案標記爲正確。 –