一尘不染

在ng-repeat中使用orderBy定制订单

angularjs

我有这样的对象:

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() {

    });
};

阅读 344

收藏
2020-07-04

共1个答案

一尘不染

嗨,您可以创建自定义排序过滤器,请参见此处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;
  };
});
2020-07-04