有人可以帮忙解释为什么第一个和最后一个选择不显示默认值吗?
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 eachoption
in theoptions
array. Because the selected option has been set programmatically in the controller, thetrack by
expression is also applied to thengModel
value. When thengModel
value isoptions[0]
and thetrack by
expression evaluates tooptions[0].id
there is no issue. When thengModel
value isoptions[0].label
and thetrack by
expression evaluates tooptions[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/