JD26
JD26

Reputation: 47

AngularJS: Fill select box based on two radio buttons

I have 2 radio groups with 2 radio buttons each, age group (AG1, AG2) and language ("one language", "multilingual"). Depending on which radio button is checked, I want to fill a select box with different options. So there's 4 different combinations = 4 different sets of options (4 AngularJS scope properties). I got it to work with one radio group using ng-model, but I can't figure out how to do this with two. I tried using jQuery but it won't work, I've been told that I shouldn't mix AngularJS and jQuery.

HTML (ng-value is obviously wrong here, I don't know what to set as value)

<div class="form-check">
   <input class="form-check-input" type="radio" name="AG" id="AG1" ng-model="values" ng-value="PD1E">
   <label class="form-check-label" for="AG1">4 - 5 years</label>
</div>
<div class="form-check">
   <input class="form-check-input" type="radio" name="AG" id="AG2" ng-model="values" ng-value="PD2M">
   <label class="form-check-label" for="AG2">6 - 7 years</label>
</div>

<div class="form-check">
   <input class="form-check-input" type="radio" name="language" id="one" ng-model="values" ng-value="PD1E">
   <label class="form-check-label" for="one">one language</label>
</div>
<div class="form-check">
   <input class="form-check-input" type="radio" name="language" id="multi" ng-model="values" ng-value="PD1M">
   <label class="form-check-label" for="multi">multilingual</label>
</div>
<br>
<select id="inputPD" class="form-control">
  <option ng-repeat="x in values">{{x}}</option>
</select>

AngularJS scope properties

$scope.PD1E = [
        "1-one", "0,3", "0,5", "0,8", "1,8", "5,9", "12,8", "32,2", "58,8", "81,6", "100,0"
    ];

$scope.PD2E = [
        "2-one", "0,7", "0,9", "2,0", "7,9", "21,3", "41,5", "100,0"
    ];

$scope.PD1M = [
        "1-multi", "2,1", "3,5", "5,6", "12,5", "19,4", "33,3", "48,6", "61,8", "82,6", "95,8", "100,0"
    ];

$scope.PD2M = [
        "2-multi", "0,5", "2,2", "7,6", "23,8", "49,2", "70,3", "100,0"
    ];

So if I select AG1 + one, it should display PD1E in the select box.

AG2 + one = display PD2E

AG1 + multi = display PD1M

AG2 + multi = display PD2M

Upvotes: 0

Views: 40

Answers (1)

georgeawg
georgeawg

Reputation: 48968

One approach is to use the ng-if directive with the options:

<select id="inputPD" ng-model="selectPD" class="form-control">
  <option ng-repeat="x in PD1E" ng-if="radio1=='1' && radio2=='E'">{{x}}</option>
  <option ng-repeat="x in PD2E" ng-if="radio1=='1' && radio2=='E'">{{x}}</option>
  <option ng-repeat="x in PD1M" ng-if="radio1=='2' && radio2=='M'">{{x}}</option>
  <option ng-repeat="x in PD2M" ng-if="radio1=='2' && radio2=='M'">{{x}}</option>
</select>

The <option> elements will only be added when the condition is true.

Upvotes: 0

Related Questions