phillip johnston phillip johnston - 2 months ago 10
AngularJS Question

Set selected option when select elements dynamically generated ng-repeat

I'm trying to dynamically generate select elements based on an array:

[
["Air travel program","Yes",[["--"],["Yes"],["No"]]],
["Car rental program","--",[["--"],["Yes"],["No"]]],
["Data management","--",[["--"],["Yes"],["No"]]],
["Group travel","--",[["--"],["Yes"],["No"]]],
["Hotel Program","--",[["--"],["Yes"],["No"]]],
["Payment systems","--",[["--"],["Yes"],["No"]]],
["Transient travel","--",[["--"],["Yes"],["No"]]],
["Travel policy","No",[["--"],["Yes"],["No"]]]
]


My HTML:

<div class="profileRow" ng-repeat="btpPDropdown in BTPProfileSelectList">
<label class="profileLabel">
{{btpPDropdown[0]}}
</label>
<select name="{{btpPDropdown[0]}}" >
<option ng-repeat="btpOption in btpPDropdown[2]">{{btpOption[0]}}</option>
</select>




This generates the select elements and options as expected but I cannot figure out how to set the default selected option, which should be {{btpPDropdown[1]}}, or Yes in the first select.
As I understand it, the select will set the selected option to a matching option string. I tried setting ng-model="{{btpPDropdown[1]}}" but this is invalid as it wouldn't be unique.
Any help to get this to work would be appreciated.

Answer

The issue with what you had was that you weren't binding the select to a model. Providing the model on the select itself allows you to bind it to the array. This way, when changing a drop down it will reflect in the actual array.

Modified code below:

<div class="profileRow"  ng-repeat="btpPDropdown in BTPProfileSelectList">
    <label class="profileLabel">
      {{btpPDropdown[0]}}
    </label>
    <select name="{{btpPDropdown[0]}}" ng-model="btpPDropdown[1]">
      <option ng-repeat="btpOption in btpPDropdown[2]" >{{btpOption[0]}}</option>
    </select>
</div>
Comments