Coop Coop - 2 months ago 11
AngularJS Question

Angular JS show input when radio checked

I have a javascript array like so:

$scope.quantityMachines = [
{ 'snippet' : 'One' },
{ 'snippet' : 'Two' },
{ 'snippet' : 'Three or more',
'extraField' : true },
{ 'snippet' : 'Not sure, need advice' }
];


Then I have a list of radio buttons generated by Angular JS using the array:

<ul>
<li ng-repeat="quantity in quantityMachines">
<input type="radio" id="quantityMachines{{$index}}" name="quantityMachines" value="{{quantity.snippet}}" ng-model="howMany" />
<label for="quantityMachines{{$index}}">{{quantity.snippet}}</label>
</li>
</ul>


This works. In the array there is an
extraField
with value
true
in one of the indexes. I need Angular to show an extra input field when a radio button with the
extraField
setting is checked. The array may change to have more than one index with the
extraField
value.

So the extra field would look something like this.

<input type="text" ng-model="extraInfo" ng-show="howMany" />


Other than knowing to use
ng-show
, I'm not sure what would be the correct way to do this. The above example of course does nothing.

PSL PSL
Answer

You could use ng-if and ng-show combination and a scope variable to keep track what is selected. ng-if will make sure the textbox is not added unwantedly to the DOM and ng-show to show and hide as the radio gets toggled.

In your input:-

<input type="text" ng-model="extraInfo" ng-if="quantity.extraField" ng-show="option.selected === howMany" />

and in your Radio add ng-click="option.selected=quantity.snippet"

<ul>
  <li ng-repeat="quantity in quantityMachines">
    <input type="radio" id="quantityMachines{{$index}}" name="quantityMachines" value="{{quantity.snippet}}" ng-model="howMany" ng-click="option.selected=quantity.snippet"/>
    <label for="quantityMachines{{$index}}">{{quantity.snippet}}</label>
    <input type="text" ng-model="extraInfo" ng-if="quantity.extraField" ng-show="option.selected === howMany" />
  </li>
</ul>

and add in your controller:-

$scope.option = { selected:'none'};

Bin

You could even use howMany to track what was selected except that you need to set it as a property to an object on the scope (Since ng-repeat creates its own child scope and proto inheritance comes to play).

So in your radio just add ng-model="option.howMany", in your controller add $scope.option = { }; and in the text box ng-if="quantity.extraField" ng-show="quantity.snippet === option.howMany"

Bin

Comments