Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...