在设置模型值时,Angular会在select元素中添加奇怪的选项

Swa*_*der 45 angularjs angularjs-directive angularjs-select

我有一个select元素定义如下:

<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>
Run Code Online (Sandbox Code Playgroud)

当我没有在包含这个select元素的指令中设置任何值时,一切正常.但是,当我执行类似的操作时newAddressForm.country_id = 98,Angular不会选择值为98的选项,而是在select元素的顶部注入一个新选项,如下所示:

<option value="? string:98 ?"></option>
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?这种格式是什么,为什么会发生这种情况?请注意,如果我console.log(newAddressForm.country_id)在指令中执行a ,我得到一个正常的"98",它在生成的HTML中只是奇怪.

编辑: 情境更新.切换到使用ng-select,但问题仍然存在.

奇怪的元素不再出现,但是,现在顶部还有另一个元素,一个只有问号?作为值,没有标签.

那就是我收集的,Angular的"none selected"选择.我仍然不明白为什么它不会选择我告诉它选择的选项.

newAddressForm.country_id = 98不动也没有结果.这是为什么?

jes*_*vrs 20

使用以下语法ng-options为我解决了这个问题:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 我对上述问题有同样的问题。我尝试按照建议使用ng-options。而且我注意到,选项值是数组的索引,而不是对象字段值。我将这段代码ng-options =“ client.id作为客户端中客户端的client.value”。并且还可以选择吗?值。 (2认同)

luc*_*uma 16

Angular不会将select元素的值设置为数组的实际值,并执行一些内部操作来管理范围绑定.请参阅Mark Rajcok在此链接上的第一条评论:

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

当用户选择其中一个选项时,Angular使用索引(或键)来查找数组(或对象)中的值 - 该查找值是模型设置的值.(因此,模型未设置为您在HTML中看到的值!这会导致很多混淆.)

我不完全确定使用ng-repeat是最好的选择.

  • 通常,在使用angular时,您不应该关注html元素的值.范围数据包含您要操作/使用的适当值. (3认同)