AngularJS orderby与数组和单独的键数组

时间:2014-10-17 00:56:04

标签: angularjs angularjs-orderby

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

某些代码实际上没有排序但会显示数据。 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>

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);