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?
try this:
assuming the structure is like @rtcherry mentioned.
If you're ok with having the chosen items being a mirror of what is in your countriesList like so:
Then here's an updated plunkr of how to accomplish what you need: http://plnkr.co/edit/qE3SJm?p=preview
If instead, you do just want the country code, when you're assigning it into the selectedCountries, you have to reference the actual location it is within the country array:
Other plunkr: http://plnkr.co/edit/ysAatS?p=preview
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 thengModel
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'sngModel
into hidden form elements.