javascript - select 的默认选项不适用于 bool 值

标签 javascript html angularjs

有人可以帮忙解释为什么第一个和最后一个选择不显示默认值吗?

angular.module('myApp', []);
angular.bootstrap(document.documentElement, ['myApp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

<div ng-init="options=[{id: false, label: 'False'}, {id: true, label: 'True'}]"></div>

<select ng-init="myVar=false" ng-model="myVar" >
  <option ng-value="false">False</option>
  <option ng-value="true">True</option>
</select>

<select ng-init="myVar2=false" ng-model="myVar2" ng-options="option.id as option.label for option in options">
</select>

<select ng-init="myVar3=false" ng-model="myVar3" ng-options="option.id as option.label for option in options track by option.id">
</select>

最佳答案

转述 ngOptions documentation页面:

In both examples, the track by expression is applied successfully to each option in the options array. Because the selected option has been set programmatically in the controller, the track by expression is also applied to the ngModel value. When the ngModel value is options[0] and the track by expression evaluates to options[0].id there is no issue. When the ngModel value is options[0].label and the track by expression evaluates to options[0].label.id (which is undefined). As a result, the model value is not matched against any <option> and the <select> appears as having no selected value.

关于javascript - select 的默认选项不适用于 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35552958/

相关文章:

jquery - 如何使用 jquery 获取没有 Id 的动态创建的子元素的高度

javascript - Angular 重复指令语法

javascript - 尝试使用 Angular.js 设置默认背景图片

javascript - 如何使对象/属性显示在指令中?

javascript - 如何在 index.html angular 8 中使用 *ngIf

javascript - 将 C# webapp 更改为使用母版页后,DatePicker 不再工作

javascript - 无法在聊天应用程序中使用 Ajax 调用从 Controller 返回 html

javascript - D3js 多折线图 mouseOver

javascript - 检测是否从同一网站打开了一个窗口

javascript - 如何在page2 input上显示page1中的输入值?