Angular 的 ng-options 没有正确显示默认值

Angular's ng-options not displaying default correctly

我 运行 遇到了 ng-options 的问题,我很难找到它。我在 select 控件中使用带有 ng-options 的字符串数组。它似乎正确跟踪,但默认月份名称未显示为页面加载下拉列表中的 selected 值。我创建了以下 jsfiddle 来说明这个问题: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();

标记:

<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>

我很确定这是操作错误,但我没有太多的谷歌搜索来寻找答案。有人有想法吗?

中的"problem"是idx其实是一个string(可以在[=14=13=]中生成的HTML中看到=] 标签).

然后,要使其正常工作,您只需将 default 设置为 string:

$scope.currentMonth = '7';

分叉 DEMO.

您可以使用以下解决方案

解决方案 1

在您的 html 文件中

<div ng-app="momentTest" ng-controller="main"> <div> <select 名称="monthPicker" ng-模型="currentMonth" ng-选项="month for month in months" > </select><br> </div> <div>

在你的 app.js

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

解决方案 2

在您的 html 文件中

<div ng-app="momentTest" ng-controller="main"> <select 名称="monthPicker" ng-模型="currentMonth" ng-选项="idx as month for (idx,month) in months" ng-init="currentMonth='0'"> </select><br> </div>

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