AngularJS - Change default option text inside ngOptions
I have a select menu with ng-options
to repeat options and I have a default <option>
inside the menu:
<select ng-model="selected" ng-options="d.id as d.value for d in data">
<option value="">Choose an option</option>
</select>
Problem: I want to make the text inside this option default change based on another property in $scope
, and I tried the following and it doesn't work:
<select ng-model="selected" ng-options="d.id as d.value for d in data">
<option value="" ng-if="!optional">Choose an option</option>
<option value="" ng-if="optional">Choose an option (optional)</option>
</select>
Only one element seems to be shown by default <option>
, so I also tried the following with ng-show
, but it doesn't work either:
<select ng-model="selected" ng-options="d.id as d.value for d in data">
<option value="">Choose an option <span ng-show="optional">(optional)</span></option>
</select>
I know you can also do <option ng-repeat>
inside the select menu, but the data for the parameters comes from an AJAX call and does not update correctly when the data first comes in, so I stick with using <select ng-options>
.
Here's a JSFiddle with a problem.
Any suggestions on how I can get this to work?
source to share
Your first attempt didn't work because, as the documentation select
in AngularJS says , only "a single hardcoded element <option>
can be nested within an element <select>
".
Your second attempt did not work because the element <option>
can only receive text "(with bindable type characters é
))" as content, not the tag you tried <span>
.
The solution is to just use interpolation:
<select ng-model="selected" ng-options="d.id as d.value for d in data">
<option value="">Choose an option {{optional ? '(optional)' : ''}}</option>
</select>
source to share
Have you tried setting the template markup text?
<select ng-model="selected" ng-options="d.id as d.value for d in data">
<option value="">{{defaultOptionText}}</option>
</select>
Working with this jsfiddle: http://jsfiddle.net/udu9byka/2/
source to share