Angular 在设置模型值时在选择元素中添加了奇怪的选项 [英] Angular adds strange options into select element when setting model value
问题描述
我有一个这样定义的选择元素:
当我没有在包含此 select 元素的指令中设置任何类型的值时,一切正常.但是当我执行类似 newAddressForm.country_id = 98
的操作时,Angular 不会选择值为 98 的选项,而是在 select 元素的顶部注入一个新选项,如下所示:
什么给?这是一种什么样的格式,为什么会发生这种情况?请注意,如果我在指令中执行 console.log(newAddressForm.country_id)
,我会得到一个正常的 "98"
,这在生成的 HTML 中很奇怪.>
情况更新. 改用 ng-select
,但问题仍然存在.
奇怪的元素不再出现,但是,现在顶部有另一个元素,一个只有一个问号 ?
作为值,没有标签.
根据我收集的信息,Angular 的 "none selected"
选项.不过,我仍然不明白为什么它不会选择我告诉它选择的选项.
执行 newAddressForm.country_id = 98
仍然没有结果.这是为什么?
Angular 不会将 select 元素的值设置为数组的实际值,而是执行一些内部操作来管理范围绑定.在此链接中查看 Mark Rajcok 的第一条评论:
https://docs.angularjs.org/api/ng/directive/select#overview
<块引用>当用户选择其中一个选项时,Angular 使用索引(或键)在数组(或对象)中查找值——查找的value 是模型设置的值.(因此,模型未设置为您在 HTML 中看到的值!这会引起很多混乱.)
我不完全确定使用 ng-repeat
是最好的选择.
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?
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.
这篇关于Angular 在设置模型值时在选择元素中添加了奇怪的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!