角增加了奇怪的选项为选择元素设置模型值时, [英] 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>
所有的时候我没有设置任何类型的值,其中包含此选择的元素指令工作正常。但是,当我做类似 newAddressForm.country_id = 98
,而不是用价值98选择该选项,角注入一个新的选择元素的顶部,就像这样:
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>
怎么办?什么样的格式,这是为什么会发生这种情况?需要注意的是,如果我做了的console.log(newAddressForm.country_id)
在指令中,我得到一个正常的98
,它在生成的HTML只是奇怪。
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.
编辑: 更新情况的转向使用 NG-选择
,但问题仍然存在。
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.
做 newAddressForm.country_id = 98
仍没有给出结果。这是为什么?
Doing newAddressForm.country_id = 98
still gives no results. Why is that?
推荐答案
角没有一个select元素的值设置为数组的实际值,并做一些内在的东西来管理范围约束力。见马克Rajcok的第一个评论在此链接:
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:
<一个href=\"http://docs.angularjs.org/api/ng.directive:select\">http://docs.angularjs.org/api/ng.directive:select
当用户选择的选项之一,角使用索引
(或键)来查找在阵列(或对象)的值 - 即搜索行动
价值是什么模式设置为。 (因此,该模型没有被设置为所述
珍惜你在HTML看看!这导致了很多困惑。)
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.)
我不能完全肯定使用 NG-重复
是最好的选择。
I'm not entirely sure using an ng-repeat
is the best option.
这篇关于角增加了奇怪的选项为选择元素设置模型值时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!