2

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

一些实际上不排序但显示数据的代码。代码笔

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

2 回答 2

2

您可以完成此操作,但我建议您改为让服务器将数据作为 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

于 2014-10-17T02:04:35.733 回答
0

作为参考,将数组与标准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);
于 2014-10-17T01:50:26.600 回答