【问题标题】:AngularJS orderby with array of arrays and separate keys带有数组和单独键的AngularJS orderby
【发布时间】:2014-10-17 00:56:04
【问题描述】:

我有从服务器以数据数组的形式返回的表格数据,以及与该数据关联的键数组。然后,我想按特定键排序。现在,我知道我可以预处理数据并将一组对象压缩在一起,但我不想这样做。有没有一种简单的内置方法可以做到这一点?

有些代码实际上并没有排序,但会显示数据。 CodePen.

JS:

var app = angular.module('helloworld', []);

app.controller('TestController', function() {
  this.headers = ['foo', 'bar'];
  this.data = [
    [ 'lol', 'wut' ],
    [ '123', 'abc' ]
  ];

  this.predicate = '';
});

HTML:

<table ng-app="helloworld" ng-controller="TestController as test">
  <thead>
    <tr>
      <th ng-repeat="heading in test.headers" ng-click="test.predicate = heading">{{ heading }}</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Predicate:</td>
      <td>{{ test.predicate }}</td>
    </tr>
    <tr ng-repeat="row in test.data | orderBy: test.predicate">
      <td ng-repeat="column in row">{{ column }}</td>
    </tr>
  </tbody>
</table>

【问题讨论】:

  • orderBy 接受一个属性并按一个方向排序。数组中没有属性“谓词”。您要过滤吗?
  • @Antiga,我意识到这一点,这就是为什么我指定代码实际上没有做任何事情的原因。如果我预先生成一个对象数组,它会起作用,但我想知道是否有一种聪明的方法可以避免这样做。
  • 我想我明白你现在在说什么了。我个人会使用 Lo-Dash 的 zipObject (lodash.com/docs#zipObject) 之类的东西,但我知道您不想这样做。希望您能找到您正在寻找的解决方案。
  • 感谢@Antiga,我怀疑没有办法解决它,但我对 Angular 还是很陌生..

标签: angularjs angularjs-orderby


【解决方案1】:

您可以做到这一点,但我建议您改为让服务器将数据作为 json 对象列表返回给您。

要对多维数组进行排序,基本上是按内部数组的索引进行排序。 您的谓词将保存您要排序的列的索引(在您的情况下为 0 或 1)

<th ng-repeat="heading in test.headers" 
    ng-click="test.predicate = $index">
            {{ heading }}
</th>

在你的控制器中创建一个排序函数,如下所示:

 this.sorter = function(item){
    return item[test.predicate];
  }

将此排序器应用为您的 orderBy 表达式,如下所示:

<tr ng-repeat="row in data | orderBy: test.sorter">

我已经为您分叉并更新了您的 CodePen:http://codepen.io/anon/pen/qvcKD

【讨论】:

  • 正是我想要的,谢谢!我没有从服务器返回它的原因是因为项目列表足够大,以至于它对每个请求发送的数据量产生了很大的影响。话虽如此..我应该看看压缩是否能解决这个问题。
【解决方案2】:

作为参考,数组与标准JS一起压缩的解决方案:

var app = angular.module('helloworld', []);

app.controller('TestController', function() {
  this.headers = ['foo', 'bar'];
  var data = [
    [ 'lol', 'abc' ],
    [ '123', 'wut' ]
  ];

  this.data = [];

  for (var i = 0, n = data.length; i < n; i++) {
    this.data.push({});
    for (var j = 0, m = this.headers.length; j < m; j++) {
      this.data[i][this.headers[j]] = data[i][j];
    }
  }

  this.predicate = '';
});

或者按照@Antiga 的建议使用 LoDash:

_.each(data, function(item) {
  this.data.push(_.zipObject(this.headers, item));
}, this);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多