Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

If you can't fix the backend, then all you need to do is write a sorting function for angular to use. In your case, in your angular controller, write

$scope.myCustomSort = function(elem)
{
  switch(elem.status)
  {
    case "Yes": return 1;
    case "Not now": return 2;
    case "No": return 3;
    case "Never": return 4;
    default: return 10;
  }
}

then, in your HTML, pass it as the orderBy function.

<myThing ng-repeat="item in items | orderBy:myCustomSort"></myThing>

As long as the myCustomSort method is available to the scope of whoever controls your ng-repeat, it will use your custom sort method.

I'll link you to the doc, though it's not obvious that you can do this unless you read the whole thing. But you can see that orderBy takes an expression, which can be your own function (or array of functions), where you can return your own custom value that will be sorted with < and >.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top