AngularJS - Sorting ng-repeat on string with numbers in them

假装没事ソ 提交于 2019-12-08 12:43:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!