我刚刚开始使用 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/