繁体   English   中英

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

[英]Angular's ng-options not displaying default correctly

我遇到了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>

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

“问题”是idx实际上是一个string (你可以在生成的HTML中看到它在option标签的value中)。

然后,为了使其工作,您只需将默认值设置string

$scope.currentMonth = '7';

分叉DEMO

您可以使用以下解决方案

解决方案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'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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