简体   繁体   中英

Orderby weighted average in angular

I am trying to sort a table by a weighted average of two columns. The weights for the columns are stored in a controller's scope. When I try to refer to these weights in my orderBy expression sorting is not done correctly.

 <tr ng-repeat = "x in fruitdata | orderBy:'cost.apples*apples + cost.oranges * oranges'">

Fiddle of what I want: https://jsfiddle.net/t3op50p9/2/

If I hard code weights instead everything works as it should

 <tr ng-repeat = "x in fruitdata | orderBy:'1.89*apples + 1.49 * oranges'">

Fiddle with hard coded weights (not what I want): https://jsfiddle.net/t3op50p9/3/

You can define a function in your scope to be used to calculate the weight for ordering

$scope.orderFn = function (fruit) {
    return fruit.apples * $scope.cost.apples + fruit.oranges * $scope.cost.oranges;
}

ng-repeat="x in fruitdata | orderBy: orderFn:true" (note: the true on the end reverses the order generated by the ordering function making the largest weight on top.)

https://jsfiddle.net/TheSharpieOne/t3op50p9/6/

You should use cost.apples & cost.oranges shouldn't be inside the ' single quotes as they are not the part of ng-repeat repeat array, so they will binded as string concatenation.

Markup

<tr ng-repeat="x in fruitdata | orderBy:cost.apples+'*apples + '+ cost.oranges+' * oranges'">
    <td> {{x.oranges}} </td>
    <td> {{x.apples}} </td>
    <td> {{x.apples * cost.apples + x.oranges * cost.oranges}} </td>
</tr>

Working Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM