[英]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.