Angular adds strange options into select element when setting model value

Swader picture Swader · May 28, 2013 · Viewed 42k times · Source

I have a select element defined as such:

<select name="country_id" id="country_id" required="required" ng-model="newAddressForm.country_id">
    <option value="">Select Country</option>
    <option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>

All works fine when I'm not setting any kind of value in the directive which contains this select element. But when I do something like newAddressForm.country_id = 98, instead of selecting the option with value 98, Angular injects a new one at the top of the select element, like so:

<option value="? string:98 ?"></option>

What gives? What sort of format is this and why does this happen? Note that if I do a console.log(newAddressForm.country_id) in the directive, I get a normal "98", it's just weird in the generated HTML.

Edit: Situation update. Switched to using ng-select, but the issue persists.

The weird element no longer appears, BUT, now there's another element at the top, one that has only a question mark ? as the value, and no label.

That's, from what I gathered, Angular's "none selected" option. I still don't understand why it won't select the option I tell it to select, though.

Doing newAddressForm.country_id = 98 still gives no results. Why is that?

Answer

jessedvrs picture jessedvrs · Jul 15, 2014

Using the following syntax with ng-options solved this problem for me:

<select name="country_id" id="country_id" required="required" ng-model="newAddressForm.country_id" ng-options="country.id as country.name for country in countries">
  <option value="">Select Country</option>
</select>