我有AngularJS购物车。我试图将所有购物车保存在Cookie中,但我遇到了问题。当我刷新页面时,我的旧购物车被移除。我想更新数量,如果产品已经在购物车中,或者如果不在购物车中,我想把它放在饼干中。这是我的代码:
$scope.cart = [];
$scope.cartList = [];
$scope.addToCart = function (car, quantity) {
if (car.toCartQty > car.quantity) {
alert("The quantity is not available");
return false;
}
var isInCart = false;
var myIndex = -1;
if (!$cookieStore.get('cook')) {
$cookieStore.put('cook', $scope.cart)
}
_.find($scope.cart, function (val, i) {
console.log($scope.cart[i]);
if ($scope.cart[i].id == car.id) {
myIndex = i;
isInCart = true;
}
})
console.log('index', myIndex, isInCart);
if (isInCart == true) {
car.quantity = car.quantity - car.toCartQty;
$scope.cart[myIndex].qty = $scope.cart[myIndex].qty + parseInt(car.toCartQty);
} else {
car.qty = parseInt(car.toCartQty);
car.quantity = car.quantity - car.toCartQty;
$scope.cart.push(car);
}
car.toCartQty = 0;
$cookieStore.put('cook', $scope.cart);
};
$scope.readCookie = function () {
$scope.cartNew = $cookieStore.get('cook');
console.log($scope.cartNew)
};
$scope.removeCart = function () {
$cookieStore.remove('cook');
}

答案 0 :(得分:0)
您可以使用angularjs-locker:
为您的项目添加储物柜并将其注入您的控制器:
yourController.$inject = ['locker'];
function yourController('locker')
{
//when you want save a data
locker.put('nameOfVariable', value);
//when you get data
locker.get('nameOfVariable');
//To create or recover your variable (cart)
if(locker.get('cartList') == null)
{
$scope.cartList = [];
}
else
{
$scope.cartList = locker.get('cartList');
}
}
我遇到了同样的问题,我用储物柜解决了这个问题。