[英]How to set default selected value in Angular Chosen?
I have a select
tag to which I am applying angular chosen. 我有一个
select
标签,我正在应用角度选择。
This is my select
tag 这是我的
select
标签
<select name="rname" id="rname" ng-model="rname" ng-init="rname='CustomReport'"
ng-options="key as value for (key , value) in reportsValuesOptions track by key" chosen>
<option value="">---Select---</option>
</select>
The above select
tag is getting populated from below object 上面的
select
标记将从下面的对象填充
$scope.reportsValuesOptions = {'Cash Position Report':'Cash Position Report','Detail Report':'Detail Report','Reconciliation Report':'Reconciliation Report','Summary Report':'Summary Report','Sweep Report':'Sweep Report','FCCS/FBPS Detail Report':'FCCS/FBPS Detail Report','CustomReport':'Custom Report Name'};
The object is a pair of values and options for select
tag where the key
is options tags value
and the value
is the option tag text
该对象是
select
标签的一对值和选项,其中key
是options tags value
, value
是option tag text
Now I want to set the default value of the select
tag to 'CustomReport'
as its option value
and 'Custom Report Name'
as its option text
from the above object, using ng-init
. 现在我想使用
ng-init
将select
标签的默认值设置为'CustomReport'
作为其option value
,将'Custom Report Name'
为上述对象的option text
。
I tried doing ng-init="rname='CustomReport'"
, but it doesn't work 我尝试过
ng-init="rname='CustomReport'"
,但它不起作用
How to set its value from object's key value pair? 如何从对象的键值对设置其值?
You can simply use ng-init like this 您可以像这样简单地使用ng-init
<select ng-init="somethingHere = options[0]"
ng-model="somethingHere"
ng-options="option.name for option in options">
</select>
The problem with your solution is since you are giving an object and AngularJS is mostly designed for arrays it causes AngularJS not to be able to track them properly. 您的解决方案的问题是因为您提供了一个对象而AngularJS主要是为数组设计的,它导致AngularJS无法正确跟踪它们。 You probably wanted to write a shorter object for
reportsValueOptions
but it should be an array of objects which has a form similar to the following: 您可能想为
reportsValueOptions
编写一个较短的对象,但它应该是一个对象数组,其形式类似于以下内容:
[
{label: 'First Label', value:'first-option'},
{label: 'Second Label', value:'second-option'}
]
Here is the modified version of your jsfiddle with modified object that also shows which one is selected. 以下是带有修改对象的jsfiddle的修改版本,该版本还显示了选择了哪一个。
You can also learn more about problems with objects here: https://docs.angularjs.org/api/ng/directive/ngOptions#complex-models-objects-or-collections- 您还可以在此处了解有关对象问题的更多信息: https : //docs.angularjs.org/api/ng/directive/ngOptions#complex-models-objects-or-collections-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.