Kuzgun
Kuzgun

Reputation: 4737

Check radio button with AngularJS

I have 2 radio buttons for gender.

<input type="radio" name="answer" value="Female" ng-model="$parent.gender" />Female
<input type="radio" name="answer" value="Male" ng-model="$parent.gender" />Male

I want to show a pre-selected form. I have the answers in an array in controller like this:

$scope.answers={gender:"Female"};

For this example, how can I set Female radio button based on answers object? Thanks in advance

Upvotes: 0

Views: 5597

Answers (3)

V31
V31

Reputation: 7666

You need to remove the $parent

from the ng-model and come up with the genders scope variable. Here is the DEMO

and code snippet:

HTML:

<div ng-app>
    <div ng-controller="test">
       <input type="radio" name="answer" value="Female" ng-model="answers.gender" />Female
       <input type="radio" name="answer" value="Male" ng-model="answers.gender" />Male
     </div>
</div>

CONTROLLER:

function test($scope){
    $scope.answers={gender:"Female"};
}

Upvotes: 2

Ben Lesh
Ben Lesh

Reputation: 108491

You didn't need $parent

If you're not in a child scope, (ala ng-repeat), you don't need the $parent:

app.controller('MainCtrl', function($scope) {
  $scope.answers = { gender: 'Female' };
});

HTML

<div ng-controller="MainCtrl">
  <input type="radio" value="Female" ng-model="answers.gender"/>
  <input type="radio" value="Male" ng-model="answers.gender"/>
</div>

When to use $parent

Given your example shows ng-model="$parent.gender", it looks like you think you need to get gender from the parent scope, this is only really necessary in an ng-repeat, which creates a child scope. You might find this when you create a list of radio buttons with a repeater:

JS:

app.controller('MainCtrl', function($scope) {
  $scope.radioItems = ['Male', 'Female', 'Other'];

  $scope.answers = {
    gender: 'Female',
  };
});

HTML:

<div ng-repeat="radioItem in radioItems">
  <input type="radio" value="radioItem" ng-model="$parent.answers.gender"/>
</div>

EDIT: More detailed explanation of what's going on.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Set your gender variable that you declared as the model:

ng-model="$parent.gender"

So, set $scope.gender = "Female" to select that radio.

Upvotes: 1

Related Questions