2015-06-29 86 views
0

我想通過兩列的加權平均值對錶格進行排序。列的權重存儲在控制器的範圍內。當我嘗試在我的訂單中引用這些權重時,表達式排序沒有正確完成。orderby加權平均值

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

撥弄我想要的東西:https://jsfiddle.net/t3op50p9/2/

如果我硬編碼的權重,而不是一切正常,因爲它應該

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

撥弄硬編碼的權重(不是我想要的):https://jsfiddle.net/t3op50p9/3/

回答

2

你可以在你的範圍定義一個函數來被用來計算權重排序

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

ng-repeat="x in fruitdata | orderBy: orderFn:true"(注:true上結尾顛倒了排序函數產生的順序在上面的最大重量。)

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

+0

看起來很酷定製filter..but在OP問題礦井改造有一定道理? –

+0

是的,很高興在模板中使用它,但是你失去了對這個功能進行簡單的單元測試的能力。 – TheSharpieOne

+1

+1,但我建議給這個函數一個更具描述性的名字,比如'getCost',或者其他的東西。這樣,它還具有在表格單元格中很好地調用的額外好處,即DRYing代碼。 – DRobinson

1

您應該使用cost.apples & cost.oranges不應該在'單引號,因爲它們不是ng-repeat重複數組的一部分,所以它們會綁定爲字符串連接。

標記

<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