2015-04-01 40 views
0

如何通過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

如果需要通過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 SataUSB Key之上。 Azerty Keyboard的小計總計爲$55.15,這是項目及其底部的最高總額。

在HTML

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

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

這裏是demo plunker

+0

這正是我想要的!非常感謝@ K.Toress! – Bellash 2015-04-01 12:35:55

+1

很高興幫助你:) – 2015-04-01 12:44:50

相關問題