问题
I have a list of objects in a table-view i would like to sort properly.
Amongst other things, my objects contain a name-field. This name field can also contain numbers, so for example:
Chairman
Seat 1
Seat 2
Seat 3
Seat 11
Seat 12
Seat 23
Secretary
This is however sorted like this:
Chairman
Seat 1
Seat 11
Seat 12
Seat 2
Seat 23
Seat 3
Secretary
This doesn't seem like a natural way of sorting my list when sorting by name.
Now i'm using the ng-repeat like this:
seat in seats | orderBy:orderField:orderReverse track by seat.id
Where orderfield
is some variable that is set when clicking the table header and orderReverse
is too for reversing.
I've tried making a custom filter to makes sure it behaves properly but i failed. It seems that Javascript just won't order it normally unless i break up the string. But i'd rather not because the data is often updated by polling. Another way would be to force leading zero's but since users are entering this stuff manually i'm not sure if i should.
Also, its not only names with numbers in them, so i can't just completely cut them off
So, any suggestions on how to make this list show normally?
Edit: cleared up some info about the problem.
回答1:
You can use a custom sort function with orderBy
(it can take custom sorting function too)
define a sort function in your controller:
$scope.sorter = function (a){
return parseInt(a.replace( /^\D+/g, '')); // gets number from a string
}
and then in your template
seat in seats | orderBy:sorter track by seat.id
Edit as per the modified problem statement:
Do manual sorting in controller instead of with ng-repeart using naturalSort
$scope.seats = [{"id": "Seat 12"},{"id": "Seat 3"},{"id": "Seat 1"},{"id": "Seat 2"},{"id": "Secretary"}];
$scope.seats.sort(function(a,b) {
return naturalSort(a.id, b.id);
})
or check this angular module http://blog.overzealous.com/post/55829457993/natural-sorting-within-angular-js and the fiddle demonstrating it - http://jsfiddle.net/wE7H2/3/
来源:https://stackoverflow.com/questions/25766876/angularjs-sorting-ng-repeat-on-string-with-numbers-in-them