使用 Angularjs 在选择下拉列表中设置默认值 [英] Setting default value in select drop-down using Angularjs
问题描述
我有一个对象如下.我必须将其显示为下拉列表:
I have an object as below. I have to display this as a drop-down:
var list = [{id:4,name:"abc"},{id:600,name:"def"},{id:200,name:"xyz"}]
在我的控制器中,我有一个带有值的变量.该值决定了在下拉列表中默认选择数组中的上述三项中的哪一项:
In my controller I have a variable that carries a value. This value decided which of the above three items in the array will be selected by default in the drop-down:
$scope.object.setDefault = 600;
当我创建一个下拉表单项时:
When I create a drop-down form item as below:
<select ng-model="object.setDefault" ng-options="r.name for r in list">
我面临两个问题:
列表生成为
the list is generated as
<option value="0">abc</option>
<option value="1">def</option>
<option value="2">xyz</option>
代替
<option value="4">abc</option>
<option value="600">def</option>
<option value="200">xyz</option>
默认情况下没有选择任何选项,即使我有 ng-model="object.setDefault"
推荐答案
问题 1:
您得到的生成的 HTML 是正常的.显然,Angular 的一个特性是能够使用任何类型的对象作为选择的值.Angular 在 HTML 选项值和 ng-model 中的值之间进行映射.另请参阅 Umur 在此问题中的评论:How do I set the valueAngularJS 的 ng-options 中的属性?
The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?
问题 2:
确保您使用以下 ng-options:
Make sure you're using the following ng-options:
<select ng-model="object.item" ng-options="item.id as item.name for item in list" />
并将其放入您的控制器中以选择默认值:
And put this in your controller to select a default value:
object.item = 4
这篇关于使用 Angularjs 在选择下拉列表中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!