technical musings of a caffeine converter


Ordering array of objects in Select Dropdown with Angular

As a newbie to angular and, in some sense, to javascript, when populating a select dropdown from an array of objects returned from my api, I fell into the trap of expecting the “| orderBy” filter to work as described. I’d already come a cropper with dynamically populated selects and trying to get the correct property to be shown so I probably should have been less surprised than I was.

Here’s the unordered select, populated from an array, ‘tenantTypes’ which itself is populated from an api call returning an array of a .net class, TenantType with the properties Id: long and Name: string.

<select ng-model="controller.registration.organisationType" ng-options="key as for (key, value) in controller.tenantTypes" class="form-control"> <option value="">Organisation Type...</option> </select>

The ng-options statement took me some time to work out, but it worked as expected so I hope to be able to simply add the following in:

| orderBy:’name’

Not happening. The ng-options statement needed some jiggery-pokery to work with the object array and so does the sorting. After looking around, I came across this excellent filter created by Justin Klemm:

Looks bang on the money so I grabbed it and added the following in:

| orderObjectBy:’name’

Still not happening: Once I’d ruled out my usual issues (reference the script, injecting it into the app module etc.), I started scratching my head. The only difference I could see was that this filter used the ng-repeat approach in its example. I knew I could have declared my select using <option ng-repeat… instead of the ng-options route but I had expected them to work the same under the bonnet. Well, if they do, then the ng-options does not work well with the custom filter as I finally managed to get my select ordering nicely by re-coding the select design to the following:

<select ng-model="controller.registration.organisationType" class="form-control"> <option value="" ng-selected="true">Organisation Type...</option> <option ng-repeat="type in controller.tenantTypes | orderObjectBy:'name'" value="{{}}">{{}} </option> </select>

Again, seasoned angular devs may be able to point out some glaring mistakes or assumptions I have made and please do, but just in case anyone else has tried or is trying the same approach, this might at least save them a couple of hours of head scratching Smile

Add comment