ttmt ttmt - 2 months ago 6
AngularJS Question

Angular show elements, radio button

in Angular I'm doing something like this to show and hide elements when a links is clicked.

<a ng-click="showEle = !showEle"><span ng-bind="showEle ? 'Hide' : 'Show'"></span> Element</a>
<div ng-if="showEle">
<div>


I need to do something similar but show a div based on a radio button being click.

<input type="radio" name="element" value="did" id="">Div One</br>
<input type="radio" name="element" value="did" id="">Div Two</br>
<div>
Div One
</div>
<div>
Div two
</div>


Both radio buttons are deselected to start then clicking either radio buttom will show either div.

Answer

You need to init scope variable before using it.

<input type="radio" name="element" value="did" ng-click="flag = 'div1'">Div One</br>

<input type="radio" name="element" value="did" ng-click="flag = 'div2'" id="">Div Two</br>

<div ng-show="flag == 'div1'">
    Div One
</div>

<div ng-show="flag == 'div2'">
    Div two
</div>

To use ng-model you need to apply two different values to both the radio button like this.

<input type="radio" name="element" ng-value="div1" ng-model="flag">Div One</br>
<input type="radio" name="element" ng-value="div2" ng-model="flag">Div Two</br>

 <div ng-show="flag == 'div1'">
     Div One
 </div>
 <div ng-show="flag == 'div2'">
     Div two
 </div>