ng-model is getting wrong value from dropdown

2019-07-11 13:53发布

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条回答
Rolldiameter
2楼-- · 2019-07-11 14:21

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.

查看更多
登录 后发表回答