I have a short form in AngularJS .
I use ng-repeat
to show genders and validate their radio buttons
The problem is that I want to get the value of the radio button selected and print this out using ng-model
.
How can achieve this?
Asked
Active
Viewed 4,606 times
5

Uli Köhler
- 13,012
- 16
- 70
- 120

Alex Garulli
- 737
- 1
- 12
- 29
-
Possible duplicated: [AngularJS - Using ng-repeat to create sets of radio inputs](http://stackoverflow.com/questions/14775981/angularjs-using-ng-repeat-to-create-sets-of-radio-inputs) – Beterraba Jan 30 '14 at 15:24
-
All the solutions are stopping the validation! pls help – Alex Garulli Jan 30 '14 at 18:09
-
it s not a duplicate cos I have validation I want to keep and the other question doesn't! – Alex Garulli Jan 30 '14 at 18:11
-
ok got it now was simple ng-show="user.selectedGender == 1"> and set variable to 1 – Alex Garulli Jan 30 '14 at 18:13
2 Answers
8
The problem is you're binding selected gender, a primitive value, to your $scope. When you use ng-repeat it creates a new scope and inherits the values from it's parent. Unfortunately, because your values are primitive (a number), they are passed by value instead of reference, so you only get one way binding. This is why it's always recommended to store values on an object in scope instead of directly.
Here's a link to a working controller: http://plnkr.co/edit/Y7sTEaYMx0aD4fPDHAMA?p=preview
I added this, and adjusted the rest of the code accordingly:
$scope.user = {
selectedGender: 'none'
}

Mike Robinson
- 24,971
- 8
- 61
- 83
-
-
1@AlexG_1010100101 That's a separate question. It's also to do with ng-repeat though. Your form is getting confused because it's trying to validate multiple elements with the same name. Read this article, it'll show you how to use ngForm to make it work: http://blog.brunoscopelliti.com/the-ngform-directive-of-angularjs – Mike Robinson Jan 30 '14 at 20:10
1
The solution by Mike Robinson is the most elegant. However, a quick fix is to add $parent:
<input type="radio" ng-model="$parent.selectedGender" name="radiob" id="{{g.id}}" value="{{g.id}}" required />{{g.name}}
This will change the selectGender in the parent scope of the ng-repeat.

Dieter De Mesmaeker
- 2,156
- 2
- 14
- 14