I have an array of countries:
var countriesList: [
{name: "Israel", code: "IL"},
{name: "India", code: "IN"},
{name: "Andorra", code: "AD"}
]
and an array of selected countries:
selectedCountries: [
{
country:"IL"
}
]
I'm using select2 for selecting countries.
I started with ng-repeat for generating the <options/>
tag:
<select
id="countriesList"
ui-select2
multiple
ng-model='data.selectedCountries'
data-placeholder='Choose or Search for Countries'
name='locations'
ng-change='geoTargetingChanged()'>
<option ng-repeat="country in data.countriesList" value="{{country.code}}">{{country.name}}</option>
</select>
this method worked well, but it caused the form to be $dirty
right at start.
so I started using the `ng-options- mechanism (after reading this answer):
<select
id="countriesList"
ui-select2
multiple
ng-model='data.selectedCountries'
data-placeholder='Choose or Search for Countries'
name='locations'
ng-change='geoTargetingChanged()'
ng-options="country.code as country.name for country in data.campaignSettings.countriesList">
<option></option>
</select>
Now the problem is that the value of the items is not the country code, it is their index in the array.
Am i missing something?
Here is a plunker.
I don't see any issue, although I did change the format of selectedCountries
to be an array of country codes (["IL", ...]
) instead of the data structure you provided ([{country:"IL", ...}]
).
Angular does generate the options using the index as the value, but the ngModel
will contain the propper value. If you are doing form submission with the select, you should be using the data out of the ngModel
instead of the data from the select in the HTML. If you need to put the data from the select on the page in a form, you could put the values of the select's ngModel
into hidden form elements.