Angular sorting by attribute and custom filter

I saw a lot of answers and documentation indicating that you can pass an array of attribute names into an Angular orderBy filter to sort by multiple fields. However, one of the attributes of my object is a number stored as text (the field can be "100", "75", "50" or "<25"). To sort these values ​​as numbers, I used:

<div ng-repeat="item in items | orderBy:sortFunction">
   {{item.itemStatus}} - {{item.itemLevel}}
</div>

//Function in controller...
$scope.sortFunction = function(item) {
   return parseInt(item.itemLevel);
}

Now I want to sort first by item.itemStatus, then by item.itemLevel as a number. Is there a way to do this without changing my data model first? I could iterate over all the elements and add a new attribute, which is itemLevel as a number, and then filter with

 ng-repeat="item in items | orderBy:['itemStatus','itemLevelAsNumber']

but I would like to know if there is a better way to do this. I tried

 ng-repeat="item in items | orderBy:['itemStatus',sortFunction]

but I think that using a function in this scenario assumes that the attribute name will be returned as a string.

Thank!

+4
source share
1 answer

The problem was with my sortFunction function. I did not realize that parseInt would only retrieve a number from a mixed value if it is the first.

 parseInt("25") === 25; //true
 parseInt("25+") === 25; //true
 parseInt("<25") === 25; //false - actually returns NaN

I updated the sortFunction function to

 return parseInt(item.itemLevel.replace('<',''));

and the layered orderBy in the view is what I thought it should be now:

 ng-repeat="item in items | orderBy:['itemStatus',sortFunction]

Thanks for the comments!

+1
source

Source: https://habr.com/ru/post/1676660/


All Articles