当某些值在标题处共享起始字母时,在下拉列表中输入时,我的 ng-model 会更新为第一个值。
<div ng-app="dropDown" ng-controller="dropDownController">
<select name="StateId" ng-model="selectedState" class="form-control" ng-change="selectedStateChanged()" ng-options="(states.Abbrev + ' - ' + states.Name) for states in states"></select>
<span>{{selectedState.Name||''}}</span>
</div>
Plnkr http://plnkr.co/edit/pLVzK18iJxrmrL9Oiw4b?p=preview
测试场景:
- 单击表单的任意部分。
- 单击 Tab 键以将焦点置于下拉列表中。
- 开始输入“TX”
结果: - “TX - TEXAS”选项显示在下拉列表中。 - $scope.selectedState 值是 {Name:'TENNESSEE'}
预期:
- “TX - TEXAS”选项显示在下拉列表中。
- $scope.selectedState 值应为 {Name:'TEXAS'}
我将使用纯 JavaScript 来解决这个问题,同时,我想知道是否有任何 AngularJS 解决方案。
提前致谢。
最佳答案
我在 select
方面也遇到了一些问题。这就是为什么添加空的 option
-tag 总是更安全!
<div ng-app="dropDown" ng-controller="dropDownController">
<select name="StateId" ng-model="selectedState" class="form-control" ng-change="selectedStateChanged()" ng-options="(states.Abbrev + ' - ' + states.Name) for states in states">
<option></option>
</select>
<span>{{selectedState.Name||''}}</span>
</div>
解决方案:http://plnkr.co/edit/LfS347JM6V7Rv5S6vPkL?p=preview
Angular Documentation解释一下问题:
If the viewValue of ngModel does not match any of the options, then the control will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
Optionally, a single hard-coded element, with the value set to an empty string, can be nested into the element. This element will then represent the null or "not selected" option.
关于javascript - ng-model 从下拉列表中获取错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32999394/