Search code examples
angularjsangularjs-ng-repeatangularjs-select

Default for ng-select not working


I have a form using a select. I'm trying to set a default value, which I want to disable, so the dropdown will show "-- select state --" as the first option and will force the user to make a selection.

My problem is it's not working and the select always starts out blank.

Here is my code:

    <select ng-model="contactEditCtrl.addressData.state" style="width: 50%;">
      <option ng-disabled="$index === 1"  ng-selected="true">--Select State--</option>
      <option value="{{state.abbreviation}}" ng-repeat="state in contactEditCtrl.states">{{state.name}}</option>
    </select>

Solution

  • The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

    In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

    Taken from here

    So I'd suggest writing it like this.

    var app = angular.module('myApp', []);
    
    // Register MyController object to this app
    app.controller('MyController', function MyController($scope) {
        this.addressData = {state: "--Select State--"};
        this.states = [{abbreviation: 'a', name:'ant'}, {abbreviation: 'b', name:'asd'}, {abbreviation: 'b', name:'asd2'}]
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <div ng-app='myApp' ng-controller='MyController as contactEditCtrl'>
        <select ng-model="contactEditCtrl.addressData.state" style="width: 50%;">
          <option value="--Select State--">--Select State--</option>
          <option ng-value="state.abbreviation" ng-repeat="state in contactEditCtrl.states">{{state.name}}</option>
        </select>
    </div>