简体   繁体   中英

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?

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 .

You can use following solutions

Solution 1

in your html file

<div ng-app="momentTest" ng-controller="main"> <div> <select name="monthPicker" ng-model="currentMonth" ng-options="month for month in months" > </select>
</div> <div>

in your app.js

$scope.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August','September','October','November','December']; $scope.currentMonth = $scope.months[0];

Solution 2

in your html file

<div ng-app="momentTest" ng-controller="main"> <select name="monthPicker" ng-model="currentMonth" ng-options="idx as month for (idx,month) in months" ng-init="currentMonth='0'"> </select>
</div>

in your app.js $scope.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August','September','October','November','December'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM