Angular ng-options破解版1.4+ [英] Angular ng-options broken 1.4+
问题描述
角度< 1.4可与ng-options一起显示,如下所示:
Angular < 1.4 works with ng-options shown as such:
<select ng-options="option.value as option.label for option in options" ng-model="selectedValue">
具有以下一系列选项:
[{ value:"4_220588",label:"dropdown 1-test value 1"},{value:"4_220589",label:"dropdown 1-test value 2"}]
如果您看到的结果与预期的HTML相同:
If you look at the resultant HTML is is as you would expect:
<select ng-options="option.value as option.label for option in options" ng-model="selectedValue" class="ng-pristine ng-valid ng-touched">
<option value="" class="">-- SELECT ONE --</option>
<option value="0" label="dropdown 1-test value 1">dropdown 1-test value 1</option>
<option value="1" label="dropdown 1-test value 2">dropdown 1-test value 2</option>
</select>
将角度版本更改为Angular 1.4+后,选项值属性就混乱了.这是使用更新版本的angular的具有相同ng-options的输出:
As soon as you change the angular version to Angular 1.4+, the option value attribute get's messed up. Here is the output with the same ng-options using a newer version of angular:
<select ng-options="option.value as option.label for option in options" ng-model="selectedValue" class="ng-pristine ng-valid ng-empty ng-touched">
<option value="" class="" selected="selected">-- SELECT ONE --</option>
<option label="dropdown 1-test value 1" value="string:4_220588">dropdown 1-test value 1</option>
<option label="dropdown 1-test value 2" value="string:4_220589">dropdown 1-test value 2</option>
</select>
如何使值仍然作为数组的索引显示?
What is the solution to getting the value to show up still as the index of the array?
以下是plnkr: http://plnkr.co/edit/3CTUI9b9nt9TGWhXDNQI5?p=preview
推荐答案
您的应用程序逻辑对下拉列表中的value
属性不敏感,因为ng-model
会正确设置模型,而无论HTML.如果您的应用程序逻辑确实希望该属性具有特定格式,则可以使用3种方式来处理
Your application logic should not be sensitive to the value
attribute in the dropdown, because ng-model
will set the model correctly regardless of what is output in the HTML. If you application logic does expect a specific format for this attribute, you have 3 ways to deal with this breaking change.
- 使用
ng-repeat
代替ng-options
.不建议使用此选项,因为它会显着更改选择列表的工作方式. - 使用
track by
子句强制执行您期望的密钥格式,即option.value as option.label for option in options track by option.value
.这假定option.value
存在,并且是您希望表示的值. http://plnkr.co/edit/TSXfkpf1lhsE9QYa2NAc?p=preview - 更改您的应用程序逻辑以期望使用
hashkey
,或者更正该逻辑,使其仅依赖于ng-model
.
- Use
ng-repeat
instead ofng-options
. This is the least recommended option, as it changes the way the select lists work significantly. - Use a
track by
clause to enforce the key format that you are expecting, i.e.option.value as option.label for option in options track by option.value
. This presumes thatoption.value
exists and is the value you wish to represent. http://plnkr.co/edit/TSXfkpf1lhsE9QYa2NAc?p=preview - Change your application logic to expect the
hashkey
instead, or preferably correct the logic so that it only relies uponng-model
.
这篇关于Angular ng-options破解版1.4+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!