Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-model data from radio button

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?

Here Plunker

like image 497
Alex Garulli Avatar asked Jan 30 '14 15:01

Alex Garulli


People also ask

How to bind radio button value in AngularJS?

The value of the checked radio button can be fetched with the help of the ng-model directive that helps to bind the data with the specific element & stores the required value in a variable, that can be utilized whenever we require that particular value.

How do you check radio button is checked or not in AngularJS?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.

What is value in radio button HTML?

Note: The value attribute defines the unique value associated with each radio button. The value is not shown to the user, but is the value that is sent to the server on "submit" to identify which radio button that was selected.

How do you use NG disability?

Definition and UsageThe ng-disabled directive sets the disabled attribute of a form field (input, select, or textarea). The form field will be disabled if the expression inside the ng-disabled attribute returns true. The ng-disabled directive is necessary to be able to shift the value between true and false .


1 Answers

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'
}
like image 61
Mike Robinson Avatar answered Oct 20 '22 11:10

Mike Robinson