ng-model 从下拉列表中获取错误值
ng-model is getting wrong value from dropdown
我的 ng-model 在下拉列表中输入时更新为第一个值,当一些值 SHARE 在标题处开始字母时。
<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
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.
我的 ng-model 在下拉列表中输入时更新为第一个值,当一些值 SHARE 在标题处开始字母时。
<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
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.