Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Changing text of default option inside ngOptions

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?

like image 474
Herman Tran Avatar asked Dec 25 '22 04:12

Herman Tran


1 Answers

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 &eacute;)" 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>
like image 146
Blackhole Avatar answered Dec 27 '22 19:12

Blackhole