我一直在尝试在 angularJS 中重写具有 localStorage 支持的购物车脚本,以便它们的数组能够在刷新或切换到另一个页面后幸存下来。然而,我似乎无法弄清楚我做错了什么。
<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>
当我为$scope.items替换所有$localStorage.items时,网站运行良好,但没有localStorage支持。我做错了什么?
错误:
类型错误: 无法读取未定义的属性"项" 在新的购物车控制器 (页.php:604( at Object.invoke (angular.js:4604( 在 T.instance (角度.js:9855( 在U (角度.js:8927( 在 g (角度.js:8226( 在 G (角度.js:8229( 角度.js:8106 角度.js:1696 在M.$eval(角度.js:16820( 在M.$apply(角度.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>
谢谢
替换
.controller('CartController', ['$scope', function CartController($scope, $localStorage, $sessionStorage) {
跟
.controller('CartController', ['$scope', '$localStorage', '$sessionStorage', function CartController($scope, $localStorage, $sessionStorage) {
这些变量不会注入到您的示例中。尝试使用像ng-annotate这样的工具来确保这种情况不会再次发生!
通过执行以下操作解决了它:
var appname = angular.module('appname', ['ngStorage']);
appname.controller('CartController', function($scope, $localStorage, $sessionStorage) {
现在它按预期工作。