1

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

George G
  • 7,443
  • 12
  • 45
  • 59
Nishant123
  • 1,968
  • 2
  • 26
  • 44
  • its better to do it from js rather than from html.. so just initialize the `$scope.rname = default-element` – harishr Aug 05 '16 at 08:34

2 Answers2

0

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>
Vicheanak
  • 6,444
  • 17
  • 64
  • 98
  • 4
    http://stackoverflow.com/a/21931119 nice copy paste skills.. Please give reference if you will copy some elses answer. – Fma Aug 05 '16 at 07:56
  • @Vicheanak I am still not getting it. From what you have said I tried this `ng-init="rname = reportsValuesOptions['CustomReport']"` but didn't work. What wrong am I doing? – Nishant123 Aug 05 '16 at 08:23
  • this would not work in case of `options ` gets fetched from `ajax` – Pankaj Parkar Aug 05 '16 at 08:46
0

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-

Fma
  • 362
  • 1
  • 11