在ng-repeat中使用orderBy的自定义订单

时间:2014-07-21 13:37:16

标签: angularjs angularjs-orderby

我有这样的对象:

students = {name: 'Aa_Student', class: 'A_Class'},
           {name: 'Ab_Student', class: 'A_Class'},
           {name: 'Ac_Student', class: 'B_Class'},
           {name: 'Ba_Student', class: 'B_Class'},
           {name: 'Bb_Student', class: 'C_Class'},
           {name: 'Bc_Student', class: 'C_Class'}

假设学生对象被洗牌。我使用ng-repeat来显示数据。我想按自定义顺序对对象进行排序。

例如,我想显示如下数据:

  Name              Class
-----------------------------
Ac_Student         B_Class
Ba_Student         B_Class
Aa_Student         A_Class
Ab_Student         A_Class
Bb_Student         C_Class
Bc_Student         C_Class

所以基本上,我想按学生的班级排序,但它首先是B_Class,然后是A_Class,然后是C_Class。另外,我想按字母顺序按学生姓名订购。我怎么能这样做?

HTML:

<table>
    <tr ng-repeat="student in students | orderBy:customOrder">
    ...
    </tr>
</table>

控制器:

$scope.customOrder = function(student) {
    $scope.students = $filter('orderBy')(student, function() {

    });
};

3 个答案:

答案 0 :(得分:20)

您好,您可以创建自定义排序过滤器,请参阅此处http://jsbin.com/lizesuli/1/edit

html:

  <p ng-repeat="s in students |customSorter:'class'">{{s.name}} - {{s.class}} </p>
      </div>

angularjs过滤器:

app.filter('customSorter', function() {

  function CustomOrder(item) {
    switch(item) {
      case 'A_Class':
        return 2;

      case 'B_Class':
        return 1;

      case 'C_Class':
        return 3;
    }  
  }

  return function(items, field) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {    
      return (CustomOrder(a.class) > CustomOrder(b.class) ? 1 : -1);
    });
    return filtered;
  };
});

答案 1 :(得分:10)

知道这已经过时但可能会为其他人派上用场......

您还可以创建一个简单的自定义排序功能。 “不太过滤”:

$scope.customOrder = function (item) {
        switch (item) {
            case 'A_Class':
                return 2;

            case 'B_Class':
                return 1;

            case 'C_Class':
                return 3;
        }
    };

然后像你想要的那样使用:

<table>
<tr ng-repeat="student in students | orderBy:customOrder">
...
</tr>

答案 2 :(得分:-1)

orderBy设置为对象的属性,只需引用标记中的属性名称:

ng-repeat="student in students |orderBy:'name' | orderBy:'class'"

DEMO