Telmo F.
Telmo F.

Reputation: 167

How to use ng-if with radio buttons?

This should be a simple question.

I'm having trouble using ng-if with radio buttons. These are my buttons:

<label class="radio-inline">
    <input type="radio" id="day_month" ng-model="day_month" name="inlineRadioOptions" value="option1"> day of the
    month
</label>
<label class="radio-inline">
    <input type="radio" id="day_week" ng-model="day_month" name="inlineRadioOptions" value="option2"> day of the
    week
</label>

How can I use ng-if to show something if the first radio button is selected?

Upvotes: 0

Views: 21877

Answers (3)

Shyam Mohan
Shyam Mohan

Reputation: 129

Seems like you need to show and hide some content based on selection of radio button. We can directly bind a Boolean value to check box and do it very easily. If you want do it with radio button please find below solution. HTML :

<body ng-app=”app”>
<div ng-controller="PageController">
<label>
    <input type="radio"  ng-model="color.name" value="Red"> Red
</label>
<label>
    <input type="radio"  ng-model="color.name" value="Green"> Green
</label><br>
<div ng-if="color.name==='Red'?true:false">
Hidden Message
</div> 
</body>

Angualr controller:

var app =angular.module("app",[]);
app.controller("PageController",function($scope){
$scope.color={name:'Green'};

});

Working example https://jsfiddle.net/mshyam83/q8vbbd8q/5/

Upvotes: 2

daan.desmedt
daan.desmedt

Reputation: 3820

The binded model day_month will be updated upon select with the value of the input. Checking if the value equals to the value will give you the possibility to check whether the input has been selected. Please see the example below.

<label class="radio-inline">
    <input type="radio" id="day_month" ng-model="day_month" name="inlineRadioOptions" value="option1"> day of the
    month
</label>
<label class="radio-inline" ng-show="day_month == 'option1'">
    <input type="radio" id="day_week" ng-model="day_month" name="inlineRadioOptions" value="option2"> day of the
    week
</label>

Upvotes: 3

zzzzBov
zzzzBov

Reputation: 179046

Your model will be updated with whatever value is in the [value] attribute, so you can check the data stored in whatever variable is specified by ng-model:

<div ng-if="day_month === 'option1'">...example...</div>

Upvotes: 1

Related Questions