0

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

2
  • 1
    Why do you have $parent on there? What's the context? Are you in a ng-repeat? Commented Aug 13, 2014 at 21:22
  • 1
    I forgot to mention, I am using ng-include to show a html template and these were in it. Commented Aug 14, 2014 at 19:36

3 Answers 3

2

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"};
}
Sign up to request clarification or add additional context in comments.

Comments

1

Set your gender variable that you declared as the model:

ng-model="$parent.gender"

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.