【问题标题】:Angular's ng-options not displaying default correctlyAngular 的 ng-options 未正确显示默认值
【发布时间】:2016-08-31 14:43:40
【问题描述】:

我遇到了一个难以追踪的 ng-options 问题。我在选择控件中使用带有 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>

我很确定这是操作员的错误,但我并没有在谷歌上搜索答案。有人有想法吗?

【问题讨论】:

    标签: javascript angularjs ng-options


    【解决方案1】:

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

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

    $scope.currentMonth = '7';
    

    分叉DEMO

    【讨论】:

    • 果然,谢谢。我以为我已经测试过了,但显然不是正确的方法。谢谢!
    【解决方案2】:

    您可以使用以下解决方案

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

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 2016-08-01
      • 2015-01-07
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多