Snsa90 Snsa90 - 1 year ago 118
AngularJS Question

AngularJS orderby refining

I have a table of names starting with a title (Mr, Mrs, etc) and dates stored as strings plus some other data.

I am currently sorting it using

<tr dir-paginate="booking in bookingResults | orderBy:sortType:sortReverse | filter:searchPassenger | itemsPerPage: 15">

How could I refine my orderBy to sort names excluding the title (Mr, Mrs, etc) and dates as parsed dates not strings.

What would be best practice here?

I don't want to change the names in the model by the way - I want the format to remain "Mr Foo" and "Mr Bar" but when I sort them I want them to act as if they were just "Foo" and "Bar".

AngularJS 1.5.6

Answer Source

getting the right data in the right format

title & name

I'd use a regexp to pull the title from the name:

var regex = /((Dr\.|Mr\.|Ms\.|Miss|Mrs\.)\s*)/gmi
objName.replace(regex, '')


I'm assuming you're getting either a date object or a standard date string. If it's the latter, just create a Date object via new Date(incomingDateString). Then you can call:

objDate.getTime() //returns epoch in milliseconds


Some people might dislike this but I hate dirtying up view controllers with methods that NG directives need to use for things like ordering. Instead, I added some ng-flagged properties using ng-init on each row item. Then I can sort based off that. I didn't do it for the date in the example but you could extrapolate and apply.

ng-init w. ng-flagged properties

<tr ng-repeat="row in vc.listData | orderBy:vc.sortKey track by $index"
    ng-init="row.$name =, '')">

So in other words your objects go from this:

    name:'Mr. Fred Rogers', 

to this thanks to ng-init:

    name:'Mr. Fred Rogers', 
    $name:'Fred Rogers', 

And then via your sorting UI, you can set your $scope.sortKey to either $name or $date.

code pen

I made a sample in code pen but I did it with my template which is coffeescript and jade. You can probably figure out what I'm doing.

pen -

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download