Search code examples
angularjsoptgroup

working with optgroup to show select options conditionally?


I am trying to show a select option box according to previous selected option box value. For that I use ng-show:

<select ng-model="formDate">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<select ng-model="whatever">
<optgroup ng-show="formDate == 'one'" label="A">
    <option value="a">a</option>
</optgroup>
<optgroup ng-show="formDate == 'two'" label="B">
    <option value="b">b</option>
     <option value="b">b</option>
      <option value="b">b</option>
       <option value="b">b</option>
        <option value="b">b</option>
         <option value="b">b</option>
          <option value="b">b</option>
            <option value="b">b</option>
     <option value="b">b</option>
      <option value="b">b</option>
       <option value="b">b</option>
        <option value="b">b</option>
         <option value="b">b</option>
          <option value="b">b</option>
</optgroup>
<optgroup ng-show="formDate == 'three'" label="C">
    <option value="c">c</option>
     <option value="c">c</option>
      <option value="c">c</option>
       <option value="c">c</option>
        <option value="c">c</option>
         <option value="c">c</option>
          <option value="c">c</option>
           <option value="c">c</option>

</optgroup>

The problem here is that third option box is not opening correctly!

What I see that If I set less options to optgroup B then third optgroup opens correctly..

Live: http://plnkr.co/edit/Q4j2hdCfiCZI1TbuwZ8v?p=preview

That bug happens on chorme but ff and on ie10 doesn't work at all..

Any tips?

Thank you in advance!


Solution

  • The right approach to switch the options would be move the options into an array variable in the controller and filter it when and where needed.

    If that doesn't work for you and want go with this implementation you will have to use ng-if instead of ng-show.

    <optgroup ng-if="formDate == 'one'" label="A">
        <option value="a">a</option>
    </optgroup>
    <optgroup ng-if="formDate == 'two'" label="B">
     <option value="b">b</option>
    </optgroup>
    

    What happens here is that all three option groups are rendered in the DOM which is syntactically wrong, which makes the browser picks up the third one by default. ng-if instead wont render the DOM unless the condition is satisfied.