我正在尝试使用自定义 orderBy 函数。最初,我希望数据按添加到的顺序显示$scope.rows
,并且只有在单击列标题后才应按特定属性排序。这是我的小提琴:
这是我的看法:
<table ng-app ng-controller="ctrl">
<tr>
<th><a ng-click="orderBy = 'id'">ID</a></th>
<th><a ng-click="orderBy = 'name'">Name</a></th>
</tr>
<tr ng-repeat="row in rows | orderBy:mySort">
<td>{{row.object.id}}</td>
<td>{{row.object.name}}</td>
</tr>
</table>
这是我的控制器:
function ctrl($scope)
{
// Initially, we don't sort by anything
$scope.orderBy = "";
$scope.rows = [];
// Add some rows
for(var i = 10;i < 30;i++)
{
$scope.rows.push({settings: {foo: true}, object: {id: i, name: "Name " + i}})
};
$scope.mySort = function(row)
{
if($scope.orderBy != "")
{
return row.object[$scope.orderBy];
}
// What do I return here??
return "";
}
}
如果$scope.orderBy
未设置并且我想按$scope.rows
原始顺序返回,我应该返回什么$scope.mySort
?我不能return row.object.id
,因为不能保证按 ID 顺序添加行。在 Chrome 32 上按原样运行我的代码,出现的第一行的 ID 为 20,即中间行。