我刚刚开始使用 AngularJS。我需要从 AngularJS 的书中升级这个购物车示例,以便所有 (items.price*item.quantity) 的总数显示在页面底部。实现它的推荐方法是什么?
<HTML ng-app>
<head>
<script src="js/angular.min.js"></script>
<script>
function CartController($scope) {
$scope.items = [{
title: 'Paint pots',
quantity: 8,
price: 3.95
},
{
title: 'Pebbles',
quantity: 5,
price: 6.95
}];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
</script>
</head>
<body ng-controller='CartController'>
<div ng-repeat='item in items'>
<span>{{item.title}}</span>
<input ng-model='item.quantity'>
<span>{{item.price}}</span>
<span>{{item.price * item.quantity}}</span>
<button ng-click="remove($index)">Remove</button>
</div>
</body>
</html>
谢谢!
最佳答案
这是一个plunker :
创建一个像这样迭代所有项目的函数:
$scope.sum = function(){
return $scope.items.reduce(function(p,item){
return p + (item.quantity * item.price)
},0)
}
标记:
<span>Sum : {{ sum() }}</span>
阅读更多关于 reduce method 的信息
关于angularjs - 汇总 Controller 中包含的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208341/