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

Angular's ng-options not displaying default correctly

本文关键字:显示 默认值 ng-options Angular      更新时间:2023-09-26

我遇到了一个ng选项的问题,我很难追踪。我在选择控件中使用带有ng选项的字符串数组。它似乎跟踪正确,但默认的月份名称没有显示为选择值在页面加载的下拉菜单中。我创建了以下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(您可以在option标记的value中生成的HTML中看到它)。

然后,为了使它工作,你只需要设置默认string:
$scope.currentMonth = '7';

fork 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'];