繁体   English   中英

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

[英]Working with local storage on AngularJS for shopping cart

我刚刚开始使用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列出购物车数组项目。 使用ng-click调用函数ng-click完成CRUD。

一切都完美。 我现在只需要能够使$scope.cart在localStorage中保持$scope.cart 检查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天,则必须重新购买。 希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM