0

I build a control using an Object that I get it from external source.

var field= {
          "attributeName": "Country",
          "dbColumnName": "location",
          "fieldType": "DROP_DOWN",
          "optionName": ['US', 'AUS', 'UK', 'IND'],
          "optionValue": ['123','456','789','0123']
        }

Control is created from above object

<select name="{{field.attributeName}}" ng-model="formControlsValues[field.dbColumnName]"/>
   <option ng-repeat="item in field.optionName track by $index" ng-value="field.optionValue[$index]">
       {{item}}
   </option>
</select>

field.optionName is an Array and item will be a display value. field.optionValue[$index] is another array mapped for values.

Marking default value in Selectbox while using above two arrays in Angular, how can it be achieved ?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
teenu
  • 684
  • 2
  • 8
  • 24

1 Answers1

2

If I got it right, you want to set a default value in the select input. Sticking with your code, I set a default_index value and used it to init input and options.

<select name="{{field.attributeName}}" 
  ng-init="field.itemsel = field.optionValue[default_index]" 
  ng-model="field.itemsel">
   <option ng-repeat="item in field.optionName track by $index" 
   ng-selected="default_index == $index"
   ng-value="field.optionValue[$index]">
       {{item}}
   </option>
</select>
<p>
  OptionValue to be used for whatever: {{field.itemsel}} 
</p>

please check this jsfiddle I created.

Additionally I would rewrite your code using ng-options (as suggested in Angular select input documentation):

<select name="{{field.attributeName}}" 
  ng-options="index as item for (index, item) in field.optionName" 
  ng-init="indexselected='1'"
  ng-model="indexselected">
</select>
<p>Selected index: {{indexselected}}</p>
<p>Option Value: {{field.optionValue[indexselected]}}</p>

check this other jsfiddle I created. If your doubt was different, please point it out more clearly.

mtb
  • 230
  • 1
  • 7
  • Bingo !! Thanks @mtb I made few changes in your code to suit my requirements. But your code in the key to lead me there.. :) – teenu Aug 04 '16 at 07:26
  • I made a small change like "ng-options='field.optionValue[index] as item..." and ng-init="formControlsValues[field.dbColumnName]=field.initialValue" and ng-model="formControlsValues[field.dbColumnName]" in the control which will collect the changed value in the control. – teenu Aug 04 '16 at 07:39