I have a select menu using ng-options
to repeat the 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 it so that the text inside that default option changes based off another property in the $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>
It seems it will only show one default <option>
element, 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 options comes from an AJAX call and doesn't update correctly when the data first comes in, so I'm sticking to using <select ng-options>
.
Here's a JSFiddle with the problem.
Any suggestions for how I could go about getting this to work?
Your first try didn't work because, as said by the documentation of select
in AngularJS, only "a single hard-coded <option>
element can be nested into the <select>
element".
Your second try didn't work because the <option>
element can only receive "text (with eventually escaped characters like é
)" as content, and not any tag like the <span>
you've tried.
The solution is simply to 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With