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.
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments