[英]AngularJS - How to preselect value in select?
我有一系列可用的选择项目:
// Default available date formats
$scope.dateformats = [
{
code: 'YY.MM.DD',
name: 'YY.MM.DD'
},
{
code: 'DD.MM.YY',
name: 'DD.MM.YY'
}
];
我正在尝试像这样默认默认值:
$scope.actualDateformat = $scope.dateformats[0].code;
<select ng-options="dateformat.name for dateformat in dateformats" ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
<option style="display:none" value="">{{actualDateformat}}</option>
</select>
问题是,“预选”值作为第一选项标签显示在列表中>
<option style="display:none" value="">{{actualDateformat}}</option>
从剩余的两个动态添加的项目中选择任何一个后,第一个选项中的文本将附加所选项目的文本(和值)。
请问如何解决?
我想要这样的结果:
<select>
<option value="YY.MM.DD">YY.MM.DD</option>
<option value="DD.MM.YY" selected>DD.MM.YY</option>
</select>
谢谢你的帮助。
这是FIDDLE
您的问题是您要选择整个对象而不是该对象的代码字段。
dateformat.name for dateformat in dateFormats
label : dateformat.name
object : dateformat
dateformat.code as dateformat.name for dateformat in dateformats
label : dateformat.name
object : dateformat.code
我也不明白display:none
option
的需要。
您可以像这样选择dateformat.code
。
<select ng-options="dateformat.code as dateformat.name for dateformat in dateformats" ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
</select>
更改:
<select ng-options="dateformat.name for dateformat in dateformats"
ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
<option style="display:none" value="">{{actualDateformat}}</option>
</select>
至:
<select ng-options="dateformat.code as dateformat.name for dateformat in dateformats"
ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
</select>
这样,select应该可以识别dateformat.code
与actualDateformat
相匹配的actualDateformat
。
举个例子:
假设:
$scope.array = [
{ key: 1, value: 'Display text 1!' },
{ key: 2, value: 'Display text 2!' },
{ key: 3, value: 'Display text 3!' }
]
然后,使用以下选项:
<select ng-options="item.key as item.value for item in array" ng-model="result">
将导致:
<select ...>
<option value="1">Display text 1!</option>
<option value="2">Display text 2!</option>
<option value="3">Display text 3!</option>
</select>
$scope.result
将设置为这些选项元素的value
属性。
如果将$scope.result
初始化为2
,则"Display text 2!"
应该选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.