使用Angularjs在选择下拉设置默认值 [英] Setting default value in select drop-down using Angularjs
问题描述
我有一个对象如下。我有显示这是一个下拉菜单:
VAR列表= {[ID:4,名称:ABC},{ID:600,名称:DEF},{ID:200,名称:XYZ }]
在我的控制器我有一个带有值的变量。此值决定该阵列中的上述三项将默认在下拉来选择:
$ scope.object.setDefault = 600;
在我下面创建一个下拉型窗体项目:
<选择NG模型=object.setDefaultNG选项=r.name在列表R>
我面临两个问题:
-
列表如下
产生<期权价值=0> ABC< /选项>
<期权价值=1>&高清LT; /选项>
<期权价值=2>&XYZ LT; /选项>而不是
<期权价值=4> ABC< /选项>
<期权价值=600>&高清LT; /选项>
<期权价值=200>&XYZ LT; /选项> -
没有选项被默认选中,即使我有
NG-模式=object.setDefault
问题1:
你要生成的HTML是正常的。显然,这是角度的功能,能够使用任何类型的对象作为价值的选择。角做的HTML期权值和NG-模型值之间的映射。
还看到在这个问题上Umur的评论:<一href=\"http://stackoverflow.com/questions/12139152/how-to-set-value-property-in-angularjs-ng-options\">How设定值属性angularjs NG选项?
问题2:
请确保您使用以下NG选项:
&LT;选择NG模型=object.itemNG选项=item.id作为item.name在列表项/&GT;
和把它放在你的控制器来选择一个默认值:
object.item = 4
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">
I face two problems:
the list is generated as
<option value="0">abc</option> <option value="1">def</option> <option value="2">xyz</option>
instead of
<option value="4">abc</option> <option value="600">def</option> <option value="200">xyz</option>
No option gets selected by default even though i have
ng-model="object.setDefault"
Problem 1:
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 to set value property in angularjs ng-options?
Problem 2:
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屋!