Dropdown in AngularJS has Correct Text, but Wrong

2019-09-09 21:56发布

问题:

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>