Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a prompt on a select using ng-options?

I have a select that uses ng-options to populate the select as follows:

<select class="form-control" 
   ng-model="Data.selectedPerson" 
   ng-options="v as (v.Name ) for v in Data.people track by v.Name">
</select>

I don't want to add a value to the collection for a default if the people collection is empty or no value is selected yet. I would like to have a prompt in the select to encourage them to use the select. Thanks for your suggestions.

like image 657
user3648646 Avatar asked Dec 26 '22 05:12

user3648646


1 Answers

Just add a default option, just so angular will use this option when there is nothing selected in the ngModel or an invalid item is populated in the model. This way you don't need to add an empty value in your collection.

<select class="form-control" 
   ng-model="Data.selectedPerson" 
   ng-options="v as v.Name for v in Data.people  track by v.Name">
   <!-- Add your default option here -->
   <option value="">Please select a person</option>

</select>

You could also change the text based on the condition:-

  <option value="">{{ Data.people.length ? "Please select a person" : "No one available for selection" }}</option>

You can also remove it from DOM if it has already a selected value.

   <option ng-if="!Data.selectedPerson" value="">Please select a person</option>
like image 176
PSL Avatar answered Dec 27 '22 19:12

PSL