首页 > 解决方案 > 如何在本地存储中的每次点击中设置记录并获取所有这些记录列表?

问题描述

当我在每次单击按钮时将对象记录存储在本地存储中时,我需要获取所有列表。

我尝试如下,但每次点击都会获得当前点击设置的相同记录,而不是之前的点击设置记录。

$scope.AddToCart = function () {
var items = [];
var listItems = {
                Garment: list.ItemName,
                Quantity: itemQty,
                Price: list.DryClean,
                Service: service,
                Total: totalPrice
            };
items.push(listItems);
localStorage.setItem('listItems', JSON.stringify(items));
var stored = JSON.parse(localStorage.getItem("listItems"));
console.log(stored);

我想得到如下

第一次点击:0: {Garment: "Thobe", Quantity: "1", Price: 5, Service: "", Total: 5}

第二次点击:

0: {Garment: "Thobe", Quantity: "1", Price: 5, Service: "", Total: 5}
1: {Garment: "Shirt", Quantity: "1", Price: 20, Service: "", Total: 25}

第三次点击:

0: {Garment: "Thobe", Quantity: "1", Price: 5, Service: "", Total: 5}
1: {Garment: "Shirt", Quantity: "1", Price: 20, Service: "", Total: 5}
2: {Garment: "Pant", Quantity: "1", Price: 30, Service: "", Total: 55}

标签: javascriptangularjs

解决方案


只是把函数放在var items = [];外面。$scope.AddToCart

var items = [];
$scope.AddToCart = function() {
    var listItems = {
      Garment: list.ItemName,
      Quantity: itemQty,
      Price: list.DryClean,
      Service: service,
      Total: totalPrice
    };
    items.push(listItems);
    localStorage.setItem('listItems', JSON.stringify(items));
    var stored = JSON.parse(localStorage.getItem("listItems"));
    console.log(stored);

推荐阅读