Angularjs 正在尝试将localStorage(ngStorage)解析为ng repeat
我已经和AngularJS玩了几天了,虽然一些灯泡开始亮起来,但我不确定为什么我不能像ng中的$scope变量那样使用我的localStorage变量。重复: 工作原理: JSAngularjs 正在尝试将localStorage(ngStorage)解析为ng repeat,angularjs,ng-storage,Angularjs,Ng Storage,我已经和AngularJS玩了几天了,虽然一些灯泡开始亮起来,但我不确定为什么我不能像ng中的$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',
$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}
];
$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 items">
<span>{{item.title}}</span>
<span>{{item.price | currency:"€"}}</span>
<span>{{item.price * item.quantity | currency:"€"}}</span>
</div>
<div ng-repeat="item in $localStorage.items">
<span>{{item.title}}</span>
<span>{{item.price | currency:"€"}}</span>
<span>{{item.price * item.quantity | currency:"€"}}</span>
</div>
HTML
<div ng-repeat="item in items">
<span>{{item.title}}</span>
<span>{{item.price | currency:"€"}}</span>
<span>{{item.price * item.quantity | currency:"€"}}</span>
</div>
<div ng-repeat="item in $localStorage.items">
<span>{{item.title}}</span>
<span>{{item.price | currency:"€"}}</span>
<span>{{item.price * item.quantity | currency:"€"}}</span>
</div>
{{item.title}
{{item.price}货币:&euro;}
{{item.price*item.quantity}货币:&euro;}
然而,这是行不通的。我做错了什么?
$localStorage
是一项服务,它不是$scope
上的属性。您可能可以执行类似于$scope.localStorage=$localStorage
的操作,然后在localStorage.items中使用项。这很有效!因此,我的信息是:通过使其成为scope的属性,它可以被ng-repeat解析和处理。通过使其成为$scope
的属性,它对带有ng controller
的HTML元素以及该元素的所有子元素可见<除了它是一个与$scope
属性交互的指令这一事实之外,code>ng repeat
实际上并不涉及。任何其他指令(ng-
)也会受到同样的影响。感谢@Claies的解释