使用 ng-repeat 对 Angularjs 表进行排序 [英] Angularjs table sort with ng-repeat
问题描述
我有一个 HTML 表格,想通过点击表格标题(ctrl 中的 $scope.headers
)对我的记录进行排序(ctrl 中的 $scope.records
),
I have an HTML table and want to sort my records ($scope.records
in ctrl) by clicking on table headers ($scope.headers
in ctrl),
谁能解释一下为什么会这样:
Can anyone explain why does that work:
<th>
<a ng-click="sortColumn=headers[0];reverse=!reverse">{{ headers[0] }}</a>
</th>
<th>
<a ng-click="sortColumn=headers[1];reverse=!reverse">{{ headers[1] }}</a>
</th>
那不会:
<th ng-repeat="header in headers">
<a ng-click="sortColumn=headers[$index];reverse=!reverse">{{ headers[$index] }}</a>
</th>
这里是记录的代码:
<tr ng-repeat="arr in records | orderBy:sortColumn:reverse">
<td ng-repeat="val in arr" ng-bind-html-unsafe="arr[headers[$index]]</td>
</tr>
我的表中有 58 列,因此循环遍历表标题会更好...
I have 58 columns in my table so would be much better to loop through the table headers...
推荐答案
正如大卫所说,这可能与范围有关.由于 ngRepeat 创建了一个新的范围,您的 ngClick
正在设置sortColumn
和 reverse
在每个列标题的自己的子范围内.
As David suggested this is likely scope related. Since ngRepeat creates a new scope your ngClick
is setting the sortColumn
and reverse
in its own child scope for each column header.
确保您在同一范围内修改值的一种解决方法是在范围内创建一个函数并在传递索引的 ngClick 中调用该函数:
One way around this to ensure you are modifying the values in the same scope would be to create a function on the scope and call that in your ngClick passing in the index:
$scope.toggleSort = function(index) {
if($scope.sortColumn === $scope.headers[index]){
$scope.reverse = !$scope.reverse;
}
$scope.sortColumn = $scope.headers[index];
}
将此作为您的标记:
<th ng-repeat="header in headers">
<a ng-click="toggleSort($index)">{{ headers[$index] }}</a>
</th>
另一种选择是绑定到这样的非原始类型(子作用域将访问同一个对象):
Another option would be to bind to a non-primitive type like this (the child scopes will be accessing the same object):
$scope.columnSort = { sortColumn: 'col1', reverse: false };
将此作为您的标记:
<th ng-repeat="header in headers">
<a ng-click="columnSort.sortColumn=headers[$index];columnSort.reverse=!columnSort.reverse">{{ headers[$index] }}</a>
</th>
这篇关于使用 ng-repeat 对 Angularjs 表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!