我一直在尝试在支持 localStorage 的 angularJS 中重写购物车脚本,以便它们的数组能够在刷新或切换到另一个页面时存活下来。但是我似乎无法弄清楚我做错了什么。
<script>
angular.module('appname', ['ngStorage'])
.controller('CartController', ['$scope', function CartController($scope, $localStorage, $sessionStorage) {
if ($localStorage.items === undefined) {
$localStorage.items = [];
}
$scope.addToCart = function(index, title, desc, price) {
var found = false;
angular.forEach($localStorage.items, function(items) {
if (items.id === index) {
items.quantity++;
found = true;
}
});
if (!found) {
$localStorage.items.push(angular.extend({id: index, title: title, quantity: 1, price: price}, index));
}
};
$scope.remove = function(index) {
$localStorage.items.splice(index, 1);
};
}])
</script>
当我将所有 $localStorage.items 替换为 $scope.items 时,网站工作正常,但没有 localStorage 支持。我究竟做错了什么?
错误:
TypeError:无法在 u (angular.js:8927) 的 T.instance (angular.js:9855) 的 Object.invoke (angular.js:4604) 的新 CartController (page.php:604) 处读取未定义的属性“项目” ) 在 g (angular.js:8226) 在 g (angular.js:8229) 在 angular.js:8106 在 angular.js:1696 在 m.$eval (angular.js:16820) 在 m.$apply (angular .js:16920)
更新 1
HTML
<!DOCTYPE html>
<html ng-app="appname">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="CartController">
<a href="javascript:void(0);" ng-click="addToCart(1,'x','y','5.00');">Toevoegen</a>
<div ng-repeat='item in items'>
{{item.title}}
{{item.price | currency:"€"}}
{{item.price * item.quantity | currency:"€"}}
</div>
</body>
</html>
JS
<script>
angular.module('appname', ['ngStorage'])
.controller('CartController', ['$scope, $localStorage, $sessionStorage', function CartController($scope, $localStorage, $sessionStorage) {
if ($localStorage.items === undefined) {
$localStorage.items = [];
}
$scope.remove = function(index) {
$localStorage.items.splice(index, 1);
};
$scope.addToCart = function(index, title, desc, price) {
var found = false;
angular.forEach($localStorage.items, function(items) {
if (items.id === index) {
items.quantity++;
found = true;
}
});
if (!found) {
$localStorage.items.push(angular.extend({id: index, title: title, quantity: 1, price: price}, index));
}
};
}])
</script>
谢谢