ng-model is getting wrong value from dropdown

寵の児 提交于 2019-12-11 04:03:19

问题


My ng-model is updated with the first value when typing in a dropdown when some values SHARE start letters at captions.

 <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

Scenario to test:

  1. Click on any part of the form.
  2. Click Tab to focus the Dropdown.
  3. Start typing 'TX'

Result: - 'TX - TEXAS' option is displayed on drowpdown. - $scope.selectedState value IS {Name:'TENNESSEE'}

Expected:

  • 'TX - TEXAS' option is displayed on drowpdown.
  • $scope.selectedState value should be {Name:'TEXAS'}

I'm gonna work this out by using plain javascript, in the meantime, I would like to know if theres any AngularJS solution out there.

Thanks in advance.


回答1:


I also experienced some problems with select. That's why it is always safer to add an empty 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>

The solution: http://plnkr.co/edit/LfS347JM6V7Rv5S6vPkL?p=preview


Angular Documentation explains the problem:

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.



来源:https://stackoverflow.com/questions/32999394/ng-model-is-getting-wrong-value-from-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!