DaveC426913 DaveC426913 - 2 months ago 9
AngularJS Question

Angular: sort the options of a select

The giant object array I've been blessed with is sorted by its code, rather than it's human-friendly name. I'd like it to display friendly.

portsService:

var _getPorts = function (){
return _portList;
}

var _portList = [{
"code": "0101",
"portOfEntry": "Portland, ME"
}, {
"code": "0102",
"portOfEntry": "Bangor, ME"
}, {
"code": "0103",
"portOfEntry": "Eastport, ME"
}, {
"code": "0104",
"portOfEntry": "Jackman, ME"
}, ...


Controller:

vm.getPortsSelect = function () {
vm.ports = portsService.getPorts();
};


View:

<select
ng-model="adminManifestVm.Manifest.usPortOfArrival"
ng-options="port.code as port.portOfEntry for port in adminManifestVm.ports"
name="usPortOfArrival"
class="form-control input-inline input-medium"
required>
<option value=""></option>
</select>


There are plenty of ways to sort an object array manually. Is there an Angular way?

Answer

You can just use the filter orderBy

ng-options="port.code as port.portOfEntry for port in adminManifestVm.ports |  orderBy:'code'"

DEMO APP

Comments