cjmling cjmling - 1 month ago 9
Javascript Question

AngularJS orderby integer field not working properly

I just took the simplest demo from http://docs.angularjs.org/api/ng.filter:orderBy and just change the value of age to have different number of digit. It stop working as it expected. Its ordering like "string" not as "integer" value. How should i change it so that it order by age like integer value?

Plunkr demo is here
http://plnkr.co/edit/pzgiIYrki7jUZdVaTMt9?p=preview

Codes are:

function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:'2352345'},
{name:'Mary', phone:'555-9876', age:'4235243'},
{name:'Mike', phone:'555-4321', age:'241'},
{name:'Adam', phone:'555-5678', age:'34325'},
{name:'Julie', phone:'555-8765', age:'1234'}]
$scope.predicate = '-age';
}


<!doctype html>
<html ng-app="App">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>

<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>


</body>
</html>

Answer

you have to convert age to type Number to make to orderBy to work as it should.

Add to your controller to sort String age as float:

   angular.forEach($scope.friends, function (friend) {
    friend.age = parseFloat(friend.age);
   });

It should work,

See PLunker