Custom order using orderBy in ng-repeat

老子叫甜甜 提交于 2020-01-09 13:04:54

问题


I have objects like this:

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'}

Let's say the students object is shuffled. I use ng-repeat to show the data. I want to sort the objects in the custom order.

For example, I want to show the data like this:

  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

So basically, I want to order by student's class, but it B_Class comes first, then A_Class, then C_Class. Also, I want to order by students name in alphabetic order. How can I do this?

HTML:

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

Controller:

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

    });
};

回答1:


Hi you can create custom sort filter please see here http://jsbin.com/lizesuli/1/edit

html:

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

angularjs filter:

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;
  };
});



回答2:


Know this is old but may come in handy for others...

You could also create a simple custom sort function. "Not quite a filter":

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

            case 'B_Class':
                return 1;

            case 'C_Class':
                return 3;
        }
    };

And then use like you wanted to:

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




回答3:


to set the orderBy as a property of the objects just quote that property name within the markup:

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

DEMO



来源:https://stackoverflow.com/questions/24866492/custom-order-using-orderby-in-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!