在AngularJS上为购物车使用本地存储

Working with local storage on AngularJS for shopping cart

本文关键字:存储 购物车 AngularJS      更新时间:2023-09-26

我刚开始使用AngularJS构建一个简单的购物车。我现在已经完成了购物车的所有CRUD操作,现在想使用本地存储将购物车保存3天。我还希望能够检查本地存储,并在用户再次访问网站时检索购物车。下面是我的代码。任何帮助都将不胜感激;

JS代码

$scope.items = <?php echo json_encode($item_array); ?>;
$scope.cart = [];
$scope.deleteItem = function(item) {
  var cart = $scope.cart;
  var match = getMatchedCartItem(item);
  if (match.count) {
    cart.splice(cart.indexOf(item), 1);
    return;
  }
}
$scope.addItem = function(item) {
  var match = getMatchedCartItem(item);
  if (match) {
    match.count += 1;
    return;
  }
  var itemToAdd = angular.copy(item);
  itemToAdd.count = 1;
  $scope.cart.push(itemToAdd);
}
$scope.incQty = function(item) {
  var match = getMatchedCartItem(item);
  if (match) {
    match.count += 1;
    return;
  }
}
$scope.decQty = function(item) {
  var cart = $scope.cart;
  var match = getMatchedCartItem(item);
  if (match.count > 1) {
    match.count -= 1;
    return;
  }
  cart.splice(cart.indexOf(item), 1);
}
$scope.subTotal = function() {
  var subtotal = 0;
  for (var i = 0, max = $scope.cart.length; i < max; i++) {
    subtotal += $scope.cart[i].price * $scope.cart[i].count;
  }
  $scope.subtotal = subtotal;
}
$scope.calcTotal = function() {
  var total = 0;
  for (var i = 0, max = $scope.cart.length; i < max; i++) {
    total += $scope.cart[i].price * $scope.cart[i].count;
  }
  $scope.total = total + $scope.qwickCharge;
}

在我的HTML中,我使用ng-repeat列出项目,使用ng-repeat列出购物车阵列项目。CRUD是使用ng-click来调用函数的。

这一切都很完美。我现在只需要能够使$scope.cart在localStorage中持久化。检查localStorage是否有购物车数据,并为用户加载这些数据。

启动时,您可以询问localStorage是否可用:

if(typeof(Storage) !== "undefined") {

如果可用,您可以检查是否已经为用户保存了数据:

if(localStorage.getItem("cart")) {
  if(checkDate(localStorage.getItem("lastSave"))) {
    $scope.cart = localStorage.getItem("cart");
  } else {
    $scope.cart = {};
  }
}

函数checkDate()应该检查数据是否仍然是新的,或者如果3天过去了,您需要加载新的数据

如果用户完成并按下保存或类似的按钮,您只需覆盖他的旧数据并保存当前日期:

localStorage.setItem("cart", $scope.cart);
localStorage.setItem("lastSave", new Date().getTime() + (3 * 24 * 60 * 60 * 1000));

CheckDate()可能看起来像这样:

function checkDate(date) {
  if(date < new Date().getTime()) {
    return false;
  }
  return true;
}

请注意,当我保存日期时发生了变化,我现在计算离今天还有3天的日期。然后在checkDate()中,您只需检查保存的日期(提前3天)是否小于我们今天的日期。如果它是少,3天结束了,你必须得到一个新的推车。希望这有帮助:)