我一直在尝试使用localStorage支持在angularJS中重写shoppingcart脚本,这样他们的数组将在刷新或切换到另一个页面后继续存在。但是,我似乎无法弄清楚我做错了什么。
<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支持。我做错了什么?
错误:
TypeError:无法读取未定义的属性“items” 在新的CartController(page.php:604) at Object.invoke(angular.js:4604) 在T.instance(angular.js:9855) 在你(angular.js:8927) 在g(angular.js:8226) 在g(angular.js:8229) 在angular.js:8106 在angular.js:1696 at m。$ eval(angular.js:16820) at 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>
由于
答案 0 :(得分:0)
替换
.controller('CartController', ['$scope', function CartController($scope, $localStorage, $sessionStorage) {
与
.controller('CartController', ['$scope', '$localStorage', '$sessionStorage', function CartController($scope, $localStorage, $sessionStorage) {
这些变量未在您的示例中注入。尝试使用像ng-annotate这样的工具来确保不再发生这种情况!
答案 1 :(得分:0)
通过执行以下操作解决了这个问题:
///<reference path="typings/angularjs/angular.d.ts" />
///<reference path="scopes.d.ts" />
import "jquery";
import "angular";
class RegisterController {
constructor($scope: ng.IRegisterScope) {
}
}
export = RegisterController;
现在它按预期工作。