简体   繁体   中英

How to set default selected value in Angular Chosen?

I have a select tag to which I am applying angular chosen.

This is my select tag

<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

$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

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 .

I tried doing ng-init="rname='CustomReport'" , but it doesn't work

How to set its value from object's key value pair?

FULL EXAMPLE

You can simply use ng-init like this

<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. 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:

[
  {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.

You can also learn more about problems with objects here: https://docs.angularjs.org/api/ng/directive/ngOptions#complex-models-objects-or-collections-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM