Angular的选项未正确显示默认值

时间:2016-08-31 03:48:38

标签: javascript angularjs ng-options

我遇到了ng-options的问题,我很难跟踪。我在select控件中使用带有ng-options的字符串数组。它似乎正确跟踪,但默认月份名称不会在页面加载下拉列表中显示为选定值。我已经创建了以下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>

我很确定它的操作员错误,但我没有太多关于答案的谷歌搜索。有谁有想法?

2 个答案:

答案 0 :(得分:2)

&#34;问题&#34;是idx实际上是string(您可以在value option标记的string中的生成HTML中看到它。

然后,为了使其工作,您只需将默认设置为$scope.currentMonth = '7';

0000000000000020 r A.15.3480
0000000000000000 r A.3.3436
0000000000000010 r A.9.3463
                 U _gfortran_reshape_r8
00000000000fbe28 C commondata_
                 U free
                 U malloc
0000000000000000 T solveeq_

分叉DEMO

答案 1 :(得分:0)

您可以使用以下解决方案

解决方案1 ​​

你的html文件中的

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

你的app.js中的

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