Angularjs表排列与NG-重复 [英] Angularjs table sort with ng-repeat

查看:200
本文介绍了Angularjs表排列与NG-重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个HTML表格,并希望我的记录($在CTRL scope.records)通过点击表头($在CTRL scope.headers)进行排序,

Hi 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>

下面是code的记录:

Here is the code for the records:

<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...

推荐答案

正如David提出有关这很可能范围。由于 ngRepeat 创建一个新的范围你的 ngClick 是设置 sortColumn 逆转在其自己的子范围为每列标题。

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>

这里是一个小提琴用一个例子。

这篇关于Angularjs表排列与NG-重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆