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