Akhil F
Akhil F

Reputation: 7740

Select keeps resetting even though model updates

Here's the html for a select I'm trying to build.

<select
  class="form-control"
  ng-options="country.code as country.name for country in countries track by country.code"
  ng-model="country_code"
  name="country_code">
</select>

The select populates, and when I chose an option the model does update. However, the select keeps resetting and I'm not sure why.

Here's a plunker: http://plnkr.co/edit/nEKP0xDhrdrIeDPml7Am?p=preview

The reason I need track by is that I'm building a form that will be submitted the old-fashioned non-ajax way.

Upvotes: 1

Views: 86

Answers (3)

jarz
jarz

Reputation: 732

Basically the use of select as and track by together is not possible

From ngOptions docs: https://docs.angularjs.org/api/ng/directive/ngOptions

Do not use select as and track by in the same expression. They are not designed to work together.

As already said, use use country as country.name.

<body ng-app="app">
<h1>Hello Plunker!</h1>
<select
  class="form-control"
  ng-options="country as country.name for country in countries track by country.code"
  ng-model="country_code"
  name="country_code">
    </select>
    {{country_code.code}}
 </body>

http://plnkr.co/edit/xa3XtyMwfJjqvCKmjCvo?p=preview

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

See the Angular documentation on ngOptions

Note: ngModel compares by reference, not value. This is important when binding to an array of objects

Instead of country.code as country.name, use country as country.name so the reference is compared correctly.

http://plnkr.co/edit/Na2tIMDLxVS19jnsU4kE?p=preview

Of course you can no longer use country_code directly -- instead you would use country_code.code (or rename the model as I have).

Your submitting of a form in a non-ajax way concerns me, though. I don't see why you would have to do that.

Upvotes: 0

maurycy
maurycy

Reputation: 8465

In that case you are better of using ng-repeat with options element

http://plnkr.co/edit/yYysAHs6Ks5cCY4ZMjyg?p=preview

<select
      class="form-control"
      ng-model="country_code"
      name="country_code">
      <option value="{{country.code}}" ng-repeat="country in countries track by country.code">{{country.name}}</option>
</select>
        {{country_code}}

Upvotes: 1

Related Questions