Dropdown in AngularJS has Correct Text, but Wrong Value

非 Y 不嫁゛ 提交于 2020-01-25 08:03:12

问题


Here's my dropdown:

<select class="form-control form-controls input-sm" ng-model="vm.retailer.state" ng-options="state.code as state.name for state in vm.states" required>
    <option value="">-- Select a State --</option>
</select>

Here's just the first state in the data:

  "State": [
    {
      "code": "AL",
      "name": "Alabama"
    },

Here's what's being rendered in the HTML:

<select class="form-control form-controls input-sm ng-pristine ng-invalid ng-invalid-required ng-touched" ng-model="vm.retailer.state" ng-options="state.code as state.name for state in vm.states" required="">
    <option value="" class="">-- Select a State --</option>
    <option value="0" label="Alabama">Alabama</option>
    ...
</select>

I've been looking around at other posts that are asking the same question, more or less, but nothing is working. I have set a break point on the method that loads the states, and I can confirm that both Code and Name are in the array being sent to the view.


回答1:


Finally found a post that had the right answer. I was missing "track by state.code". That did the trick.

<select class="form-control form-controls input-sm" ng-model="vm.retailer.state" ng-options="state.code as state.name for state in vm.states track by state.code" required>
    <option value="">-- Select a State --</option>
</select>


来源:https://stackoverflow.com/questions/33786086/dropdown-in-angularjs-has-correct-text-but-wrong-value

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