LatencyMachine LatencyMachine -4 years ago 212
AngularJS Question

Angularjs ng-options using number for model does not select initial value

I'm trying to use ng-options with a

to bind a numeric integer value to a list of corresponding options. In my controller, I have something like this:

myApp.controller('MyCtrl', function() {
var self = this;

var unitOptionsFromServer = {
2: "mA",
3: "A",
4: "mV",
5: "V",
6: "W",
7: "kW"

self.unitsOptions = Object.keys(unitOptionsFromServer).map(function (key) {
return { id: key, text: unitOptionsFromServer[key] };

self.selectedUnitOrdinal = 4; // Assume this value came from the server.


<div ng-controller="MyCtrl as ctrl">
<div>selectedUnitOrdinal: {{ctrl.selectedUnitOrdinal}}</div>
<select ng-model="ctrl.selectedUnitOrdinal" ng-options=" as unit.text for unit in ctrl.unitsOptions"></select>

And here's a jsFiddle demonstrating the problem, and some other approaches I've taken but am not happy with.

The select option is being initialized with an empty value, instead of "mV" as expected in this example. The binding seems to work fine if you select a different option -- selectedUnitOrdinal updates properly.

I've noticed that if you set the initial model value to a string instead of a number, then the initial selection works (see #3 in the fiddle).

I really would like ng-options to play nice with numeric option values. How can I achieve this elegantly?

Answer Source

Angular's documentation for the ng-select directive explains how to solve this problem. See (last section).

You can create a convert-to-number directive and apply it to your select tag:


module.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return val != null ? parseInt(val, 10) : null;
      ngModel.$formatters.push(function(val) {
        return val != null ? '' + val : null;


<select ng-model="" convert-to-number>
  <option value="0">Zero</option>
  <option value="1">One</option>
  <option value="2">Two</option>

Note: I found the directive from the doc does not handle nulls so I had to tweak it a little.

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