Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-orderby

Orderby using a function AngularJS


I'm using ng-repeat to list off items from an array of objects. I would like to sort these items using orderBy (or perhaps some custom ordering filter.)

However, the field I want to order by is not held within the array of objects itself, but rather, it's something I have a function that I can use to calculate it for each individual object; but it requires passing each individual object into it to do so.

Something like this:

<table>
    <tr ng-repeat="item in sortedItems = (items | orderBy:'getStatus(item)':reverse)">
        <td>Title: {{item.title}}</td>
        <td>Status: {{getStatus(item)}}</td>
    </tr>
</table>

Where getStatus is inside the controller as:

$scope.getStatus = function(item){
    var days = item.days
    if(days<=100){
        var x=100-item.days+" ";
        if(days===99){
            return x+"day left";
        }
        return x+"days left";
    }
    return "Completed";
};

So it returns a string.

Is there any way I can sort by a function that requires each individual item in the array, in order to sort the way?


Solution

  • Sure, just remove the parameter from the orderBy clause, it expects the individual item:

    <tr ng-repeat="item in sortedItems = (items | orderBy: getStatus :reverse)">