1

I am trying to add a default option to a select with angular but it adds a blank option which strangely disappears when I select it.

I am getting the object to bind to the select using ng-options like this. I am appending a default option like this:

var DocumentSearchController = function (documentsService) {
    documentsService.getDocTypes().then(function (results) {
        this.documentTypes = results.data;
        this.documentTypes.unshift({ DocumentTypeID: null, Name: 'Select a Document Type' });
    }.bind(this));

The structure of the objects is:

[{DocumentTypeID: 1, Name: 'Blah'}]

I then use ng-options to bind the objects:

<select class="form-control"
        id="documentTypeSelector"
        name="documentTypeSelector"
        ng-model="vm.selectedDocumentType"
        ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID">
</select>

Then annoying this is that a blank option is strangely added that is removed when I select an item.

The options are also not ordered so I suspect my list comprehension is wrong.

2 Answers 2

1

To define a default <select> element just assign to ng-model binded variable a default value available in one <option> element (or value).

In your case vm.selectedDocumentType should be set to a vm.documentTypes[theIndexYouChoose].DocumentTypeID

More in general a simplified example could be

// given $scope.options = [1, 2, 3];
<select ng-init="selectedOption=1" ng-option="option for option in options" ng-model='selectedOption'>
</select>

You will find no empty options and the selected option will be 1

Sign up to request clarification or add additional context in comments.

Comments

0

You can add an default value this way :

<select class="form-control"
        id="documentTypeSelector"
        name="documentTypeSelector"
        ng-model="vm.selectedDocumentType"
        ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID">
    <option value="">Select a Document Type</option>
</select>

Edit Or using init function

<select class="form-control"
        ng-init="vm.selectedDocumentType= vm.documentTypes[0]" 
        id="documentTypeSelector"
        name="documentTypeSelector"
        ng-model="vm.selectedDocumentType"
        ng-options="option.Name for option in vm.documentTypes | orderBy:'option.DocumentTypeID':false track by option.DocumentTypeID">
</select>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.