【问题标题】:Sort table by column header in AngularJS在AngularJS中按列标题对表格进行排序
【发布时间】:2018-03-22 23:19:38
【问题描述】:

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

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

这是错误信息:

[orderBy:notarray] 预期的数组但已收到:0

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

【问题讨论】:

  • 尝试不同的顺序:ng-repeat="rows in $ctrl.myArray | orderBy:orderByField:reverseSort track by $index"
  • @AlekseySolovey 我试过这样,但只有标题的箭头在改变,当我点击它时,它从^ 变为v,但下面的数据保持不变。我看到了这种方法here,但还没有解决我的问题
  • @dadsa 问题在于您显示数据的方式,它不会对原始数组进行排序,而是创建一个新数组。而不是{{$ctrl.myArray[$index].name}} 使用{{rows.name}} 等。
  • @AlekseySolovey 你是对的!这就是问题

标签: javascript angularjs


【解决方案1】:

所以,这个问题与track by $index 有关。你放错地方了。

我已经为它做好了准备。以下是链接:

https://plnkr.co/edit/mqA1ofIRUAxal8d8tCr0?p=preview

【讨论】:

  • OP 使用 ControllerAs 语法
  • @AlekseySolovey,所以这不是问题。我只是给了他一个解决方案。这是可以理解的。
  • @SurjeetBhadauriya,您的解决方案效果正确,但没有解决我的问题。正如@AleksetySolovey 在评论中所说,我的特定问题的解决方案是使用{{$ctrl.myArray[$index].name}} 而不是使用{{rows.name}}
  • 是的,使用 $ctrl.myArray 但不要使用 $index 来显示值。请阅读官方网站上的 ng-repeat 以获得更清晰的想法。您以错误的方式使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 2015-09-13
  • 2013-10-08
  • 2019-07-26
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多