javascript - 在 AngularJS 上使用本地存储来存储购物车

标签 javascript php jquery angularjs

我刚刚开始使用 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 天已过,您必须购买新的购物车。希望这有帮助:)

关于javascript - 在 AngularJS 上使用本地存储来存储购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756650/

相关文章:

php - 如何迭代 SimpleXMLElement 对象的 XML 值

php - 在 AJAX 中编写 if/else 语句

javascript - 在 jQuery 中,当单选按钮都具有相同的名称时,如何获取它们的值?

javascript - 为什么要在Component中写Object=Object才能在Angular中获取Object.keys?

javascript - typescript :如何管理类型声明冲突的依赖关系?

javascript - 如何在屏幕的特定位置创建一个 div?

javascript - 您知道有一个 JavaScript 库可以让您嵌入实时更新网页格式的文本区域吗?

php 获取空闲空间/dev/sda linux

php - 从一个单词之后但另一个单词之前的字符串中获取特定单词?

javascript - 有什么方法可以让这个 jQuery 在 IE8 中工作吗?