Search code examples
angularjsangularjs-orderby

orderBy order numbers in AngularJS


I have a JSON feed which contains array of objects. Each array has a field called "status" with following values - Yes, No, Not Now, Never I want to assign an order number to it

So

Yes(1) , 
Not Now(2), 
No(3), 
Never(4)

Now whenever I sort the table which contains this status. It must be sorted by orderNo. of the status and not alphabetically.

I don't need complete answer, just a point to right direction will be enough.


Solution

  • You can add a field called orderNo to each object and populate this value with the order you defined after you retrieved the value from API.

    [
        {
            "status": "Yes",
            "orderNo": 1,
            ....
        },
        {
            "status": "Never",
            "orderNo": 4,
            ....
        }
    ]
    

    You can process it in the callback of the $http or $resource service like this:

    angular.forEach(objects, function(o){
        if(o.status === 'Yes') o.orderNo = 1;
        else if(o.status === 'Not Now') o.orderNo = 2;
        else if(o.status === 'No') o.orderNo = 3;
        else if(o.status === 'Never') o.orderNo = 4;
    });