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

末鹿安然 提交于 2019-12-04 03:49:16

问题


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>


来源:https://stackoverflow.com/questions/25556105/how-do-i-set-a-prompt-on-a-select-using-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!