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

2019-02-24 05:47发布

问题:

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.

回答1:

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>