Set default value of select to null option

David says Reinstate Monica picture David says Reinstate Monica · Oct 2, 2014 · Viewed 10.9k times · Source

According to the Angular documentation, you can create a null option that is not part of your model. This allows you to have a descriptive option. I.E. in their example they have -- choose color --. How can I make the null option the default option? I want the user to see this descriptive null option when they first load the page.

Bonus points if you can also tell me how to make the null option be disabled via angular.

Answer

ababashka picture ababashka · Oct 2, 2014

The value is set to null automatically. But if you receive data from REST for exaple and it will be set to some value - you can add ng-init to your select tag. And for disable null option after selection of some value - you need to add ng-disabled to your option tag.

<select ng-model="model" ng-options="item for item in items" ng-init="model = null">
  <option value="" ng-disabled="!!model">--Select option--</option>
</select>

And in controller:

.controller('MainCtrl', function($scope) {
  $scope.model = 'First';
  $scope.items = ['First', 'Second', 'Third'];
});

Demo: http://plnkr.co/edit/esoX26I9bESE59yneOvv