Search code examples
javascriptangularjsng-optionsangular1.6

Upgrade to Angular 1.6 breaks select dropdown


I have an app built using Angular 1.5 where the following code works just fine:

      <div class="select-wrapper">

        <select ng-model="myModel"
          ng-options="thing as thing for (thing, otherThing) in sortedThings">

          <option value="">MAKE SELECTION</option>

        </select>

        <i class="fa fa-angle-down" title="Select Arrow"></i>

      </div>

However, when I upgraded to Angular 1.6 this code no longer shows the default option in the select box (MAKE SELECTION).

Why did this happen and how to fix?

EDIT: What I want to see is, when I first load page, the dropdown should have 'MAKE SELECTION' already selected.


Solution

  • When setting the model to the default option it is important to use the value undefined. Setting the model to the empty string "" wont work.

    angular.module('defaultSelectValue', [])
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.data = {
         sortedThings: {
           a: 'fred',
           b: 'narf',
         },
         selectedOption: undefined //This sets the default value of the select in the ui
         };
      
        $scope.s2 = { 
           selectedOption: ""   //setting to empty string won't work
        }
     }]);
    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app="defaultSelectValue" ng-controller="ExampleController">
        <select
          ng-options="key as key for (key, value) in data.sortedThings"
          ng-model="data.selectedOption">
          <option value="">MAKE SELECTION</option>
        </select>
        <br>
        <tt>option = {{data.selectedOption}}</tt><br/>
        <hr>
          Empty string doesn't work<br>
        <select
              ng-options="key as key for (key, value) in data.sortedThings"
              ng-model="s2.selectedOption">
          <option value="">MAKE SELECTION</option>
        </select>
        <br>
        <tt>option = {{s2.selectedOption}}</tt>
    </body>