Search code examples
angularjsangularjs-ng-repeatangularjs-filterangularjs-orderby

Sort ng-repeat tags by custom list?


My ng-repeat show big data , and after groupBy it divides in 5 divs

<div ng-repeat=" (key, value) in gamesList | groupBy: 'id' ">...</div>

ID value is

{ '1' , '2' , '3' , '4' , '5' } 

and in result it orders from min to max .

How can I order it with my custom rule, like this:

{'5' , '2' , '4' , '1' , '3' }

Solution

  • You Can sort your data using sort() function instead of using filter. You have to define your rule like this :

    var myRule = {'5':1,'2':2,'4':3,'1':4,'3':5}
    

    And then you have to apply your custom rule over your data.

    scope.gameList=scope.gameList.sort(function(a,b){
      return myRule[a.id]>myRule[b.id];
    });
    

    You can do this by using custom filter as follows :

    myApp.filter('myFilter', function() {
     return function(input) {
       var output;
       var myRule = {'5':1,'2':2,'4':3,'1':4,'3':5};
    
       output = input.sort(function(a, b) {  
        return myRule[a.id]>myRule[b.id];
       });
    
       return output;
      }
    });
    

    And You can apply your custom filter like this :

    <div ng-repeat="d in data | myFilter">
    

    Here is an example on plunker. Hope this would help you!