我已经用 AngularJS 玩了几天了,虽然一些灯泡开始亮起,但我不知道为什么我不能像我在 ng-repeat 中的 $scope 变量一样使用我的 localStorage 变量:
什么工作:
JS
$scope.items = [
{id: 1, title: 'a', desc: '1', quantity: 1, price: 14.50},
{id: 2, title: 'b', desc: '2', quantity: 1, price: 25.95},
{id: 3, title: 'c', desc: '3', quantity: 1, price: 22.50}
];
HTML
<div ng-repeat="item in items">
<span>{{item.title}}</span>
<span>{{item.price | currency:"€"}}</span>
<span>{{item.price * item.quantity | currency:"€"}}</span>
</div>
到目前为止没有问题。但是,当我将相同的信息存储在 $localStorage.items 变量中时,它不再被正确解析到 ng-repeat 字段中。当我将它们作为函数调用时,其他将返回特定变量的函数正在工作({{example()}})
所以我想做的是:
JS
$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));
}
};
HTML
<div ng-repeat="item in $localStorage.items">
<span>{{item.title}}</span>
<span>{{item.price | currency:"€"}}</span>
<span>{{item.price * item.quantity | currency:"€"}}</span>
</div>
但是,这是行不通的。我究竟做错了什么?