risingfish risingfish - 3 months ago 7
Javascript Question

Angular's ng-options not displaying default correctly

I'm running into an issue with ng-options that I am having difficulty tracking down. I am using an array of strings with ng-options in a select control. It seems to be tracking correctly, but the default month name isn't displaying as the selected value in the dropdown on page load. I've created the following jsfiddle to illustrate the issue: https://jsfiddle.net/risingfish/ktocfrhn/13/

Javascript:

var myApp = angular.module('momentTest', []);

myApp.controller('main', function ($scope) {
$scope.months = moment.months();
$scope.currentMonth = 7;
});

myApp.run();


Markup:

<div ng-app="momentTest" ng-controller="main">
<div>
<select name="monthPicker" ng-model="currentMonth" ng-options="idx as month for (idx, month) in months">
</select>
</div>
&nbsp;
<div>
Current month: <span ng-bind="currentMonth"></span>
</div>
</div>


I'm pretty sure it's operator error, but I'm not have much look googling for the answer. Any one have an idea?

Answer

The "problem" is that the idx actually is a string (you can see it in generated HTML in the value of option tag).

Then, to make it work you just need to set the default as string:

$scope.currentMonth = '7';

Forked DEMO.