如何按getTotal()
订购,然后按数量下降?
<!DOCTYPE html>
<html ng-app="shop">
<head>
<script
src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-controller='productCtrl'>
<ul>
<li ng-repeat="x in products| orderBy:'price'">
{{x.quantity}} {{x.Name}}
<strong>{{ (x.quantity*x.price)|currency}}</strong>
</li>
</ul>
<p>Total = {{ (getTotal()) | currency }}</p>
</div>
<script>
var app=angular.module("shop",[])
.controller('productCtrl',function($scope){
$scope.products=[{quantity:4,price:42.3,Name:"HDD Sata"},
{quantity:14,price:2.83,Name:"USB Key"},
{quantity:5,price:11.03,Name:"Azerty Keyboard"},
{quantity:1,price:4.3,Name:"Mouse"}];
$scope.getTotal=function(){
var sum=0;
for(var i=0;i<$scope.products.length;i++){
sum+=($scope.products[i].price*$scope.products[i].quantity);
}
return sum;
}
});
</script>
</body>
</html>
答案 0 :(得分:1)
如果您需要按getTotal()
排序,那么该函数将只返回一个值(所有项目值的总和),因此使用该函数进行排序没有用处。我认为你需要按项目总数而不是所有项目总数进行排序:
尝试这个,
例如:考虑以下数据
$scope.products = [{
quantity: 4,
price: 1,
Name: "HDD Sata"
}, {
quantity: 2,
price: 2,
Name: "USB Key"
}, {
quantity: 5,
price: 11.03,
Name: "Azerty Keyboard"
}, {
quantity: 1,
price: 4.3,
Name: "Mouse"
}];
我认为您需要HDD Sata
位于最前面且Azerty Keyboard
位于底部,因为HDD Sata
的总价格为$4.00
,同时USB Key
也$4.00
但HDD Sata
有4 quantity
而USB Key
有2 quantity
,而您需要DESCENDING
的数量,HDD Sata
位于USB Key
之上。 Azerty Keyboard
的小计为$55.15
,这是项目的最高总计及其底部。
,
<li ng-repeat="x in products| orderBy:[getTotalForItem, '-quantity'] ">
在Controller中,
$scope.getTotalForItem = function(item) {
return item.price * item.quantity;
}