AngularJS weird behavior with html <select> tag

Issue

I am new AngularJS framework. I have few questions related to use of <select> tag in angularjs.

Firstly, whenever I am putting the first value of the option in the <select> tag, it shows an extra blank option in the drop down. Then, when I select any of the options in the dropdown, it disappears.

Secondly, whenever I am keeping any of the options blank, then it behaves normally.

Why is it happening.?

Here’s the code:

<html>
  <head>
    <title>AngularJS Binding</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>

  </head>

  <body ng-app="app">

    <div>
        Search 1: <select ng-model="optval1" >
                  <option value="any">Any</option> 
                  <option value="name">Name</option>
                  <option value="city" selected>City</option>
                </select>
              <br>
        Selected Value={{optval1}}<br><br>
        Search 2: <select ng-model="optval2" >
                  <option value="">Any</option> 
                  <option value="Name">Name</option>
                  <option value="City">City</option>
      >          </select>
              <br>
        Selected Value={{optval2}}
    </div>
  </body>
 </html>

Solution

You can use ng-init to load the initial value.

<select ng-model="optval1" ng-init="optval1='any'">
                  <option value="any">Any</option> 
                  <option value="name">Name</option>
                  <option value="city">City</option>

</select>

If you don’t want to use initial value using ng-init.

use ng-show/ng-if.

<select ng-model="optval1">
    <option value="" ng-if="false"></option>
    <option value="any">Any</option> 
    <option value="name">Name</option>
    <option value="city">City</option>
</select> 

You can also hard-coded style element to the first dropdown value.

For ex:

<select ng-model="optval1">
       <option style="display:none" value="">select</option>
       <option value="any">Any</option> 
        <option value="name">Name</option>
        <option value="city">City</option>
</select>

Does the same thing like ng-if/ng-show.

Hope this solves your problem and informative as well.

Answered By – Kishor Velayutham

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published