如何按范围功能排序,然后按字段排序

时间:2015-04-01 07:53:30

标签: angularjs

如何按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>

1 个答案:

答案 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.00HDD Sata4 quantityUSB Key2 quantity,而您需要DESCENDING的数量,HDD Sata位于USB Key之上。 Azerty Keyboard的小计为$55.15,这是项目的最高总计及其底部。

HTML中的

<li ng-repeat="x in products| orderBy:[getTotalForItem, '-quantity'] ">

在Controller中,

$scope.getTotalForItem = function(item) {
  return item.price * item.quantity;
}

这是demo plunker