Bellash
Bellash

Reputation: 8184

How to Order by Scope function and then by a field

How can I order by getTotal() and then by quantity descending?

<!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>

Upvotes: 0

Views: 131

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

If you need to order by getTotal() then that function will return only one value (total of all the item values) so there is no useful of using that function to order. I think you need to order by item totals instead of all item total:

try this one,

Ex: consider following data

 $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"
}];

I think you need HDD Sata on top and Azerty Keyboard on bottom, because total price for HDD Sata is $4.00 meanwhile USB Key also $4.00 but HDD Sata has 4 quantity while USB Key has 2 quantity and u need quantity to be DESCENDING so HDD Sata in top of USB Key. Azerty Keyboard has subtotal of $55.15 which is highest total for a item and its in bottom.

in HTML,

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

in Controller,

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

here is the demo plunker

Upvotes: 1

Related Questions