Javascript 在AngularJS中按列标题对表进行排序

Javascript 在AngularJS中按列标题对表进行排序,javascript,angularjs,Javascript,Angularjs,有一个对象数组,我从中获取数据以放入表中: $ctrl.myArray = [ {name: "name1", id: 1, children: ["one", "two"]}, {name: "name2", id: 2, children: ["two"]}, {name: "name3", id: 3, children: ["one", "two"]}, {name: "name4", id:

有一个对象数组,我从中获取数据以放入表中:

$ctrl.myArray = [
            {name: "name1", id: 1, children: ["one", "two"]},
            {name: "name2", id: 2, children: ["two"]},
            {name: "name3", id: 3, children: ["one", "two"]},
            {name: "name4", id: 4, children: ["one"]}
];
将数据放入表中工作正常,当我想添加按列排序功能时,问题就出现了

在控制器的构造函数中,我添加了以下内容:

this.orderByField = 'name';
this.reverseSort = false;
首先,我尝试只为
name
列添加排序功能,代码如下:

<thead>
    <tr>
      <th>
        <a href="#" ng-click="orderByField='name'; reverseSort = !reverseSort">
            Name <span ng-show="orderByField == 'name'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
            </a>
      </th>
      <th>Id</th>
      <th>Children</th>
    </tr>
</thead>

<tbody>
    <tr ng-repeat="rows in $ctrl.myArray track by $index | orderBy:orderByField:reverseSort">
        <td>
            {{$ctrl.myArray[$index].name}}
        </td>
        <td>{{$ctrl.myArray[$index].id}}</td>
        <td><span ng-repeat="rows in $ctrl.myArray[$index].children track by $index">
            {{$ctrl.myArray[$parent.$index].children[$index]}}</span>
        </td>
    </tr>
</tbody>

身份证件
儿童
{{$ctrl.myArray[$index].name}
{{$ctrl.myArray[$index].id}
{{$ctrl.myArray[$parent.$index].children[$index]}
这是错误消息:

[orderBy:notarray]应为数组,但已收到:0


不知道为什么数组是0。有什么想法吗?

所以,这个问题与
按$index跟踪有关。你把它放错地方了

我已经为此付出了代价。以下是链接:


可能重复的尝试不同顺序:
ng repeat=“rows in$ctrl.myArray | orderBy:orderByField:reverseSort track by$index”
@AlekseySolovey我尝试过这样做,但只有标题的箭头在更改,当我单击它时,它从
^
更改为
v
,但下面的数据保持不变。我看到了这种方法,但没有解决我的问题yet@dadsa问题在于您显示数据的方式,它没有对原始数组排序,而是创建了一个新数组。不要使用
{{$ctrl.myArray[$index].name}
而使用
{{rows.name}
等@AlekseySolovey你说得对!这就是问题所在syntax@AlekseySolovey,所以这不是问题所在。我只是给了他一个解决办法。这是可以理解的。@SurjeetBhadauriya,你的解决方案得到了正确的结果,但没有解决我的问题。正如@AleksetySolovey在评论中所说的,我的特定问题的解决方案不是使用
{$ctrl.myArray[$index].name}
来使用
{{rows.name}
是使用$ctrl.myArray,但不要使用$index来显示值。请阅读官方网站上的ng repeat,以获得更清晰的想法。你用错了它。