angularjsangularjs-directiveangularjs-select

Angular adds strange options into select element when setting model value


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?


Solution

  • Angular does not set the value of a select element to the actual values of your array and does some internal things to manage the scope binding. See Mark Rajcok's first comment at this link:

    https://docs.angularjs.org/api/ng/directive/select#overview

    When the the user selects one of the options, Angular uses the index (or key) to lookup the value in array (or object) -- that looked-up value is what the model is set to. (So, the model is not set to the value you see in the HTML! This causes a lot of confusion.)

    I'm not entirely sure using an ng-repeat is the best option.