So I am trying to bind radio buttons to objects. I have spent like an hour trying to figure this up and at last admit defeat. Here's what I got:
<table>
<tr ng-repeat="theCustomer in customers">
<td>
<input type="radio" ng-model="currentCustomer" value="theCustomer" id="{{theCustomer.id}}" ng-change="currentCustomer = theCustomer">
<label for="{{theCustomer.id}}">{{theCustomer.name}}</label>
</td>
</tr>
</table>
The angular stuff:
bankApp.controller("BankController", function ($scope, CustomerRepository)
{
$scope.customers = [];
$scope.currentCustomer = {};
$scope.createCustomer = function () {
CustomerRepository.save($scope.customer, function (customer) {
$scope.customers.push(customer);
$scope.customer = {};
});
};
});
Currently, when I try and click on a radio button nothing happens, it doesn't even get checked. I'm sure there's got to be a really simple solution to this. The end goal is to have currentCustomer
hold the customer reflected in the radio selection.
Learn how to data bind radio buttons in Angular using unidirectional data flow. Assume you have a simple list or table of elements, each row having a radio button. The user can select one of the rows and your task is to determine the selected row entry. We basically need to establish some data binding between our data and the radio buttons.
To set selected state of radio buttons in Angular we need to pass the radio button’s value to the formcontrol array like given below. To validate radio buttons in Angular we need to import the Validators service from @angular/forms.
Template-driven Radio Buttons Validation in Angular In order to implement Angular vlidation on radio buttons, use the following code. app.component.html Form starts --><form#myForm="ngForm"(submit)="submitForm(myForm)"novalidate><!--
Components such as autocomplete, date picker, slider, menus, grids, toolbars, and radio buttons are generally used using Angular Material. A radio button is a simple input element with a type property set to radio.
<input type="radio" ng-model="$parent.currentCustomer" name="foo" ng-value="theCustomer" id="{{theCustomer.id}}">{{theCustomer.name}}</td>
The key here is the ng-value="theCustomer
. This is how angular knows which object is selected. The html value
only knows string values and cannot map to objects.
If you insert the above code, the radio will reflect the model, even if it is changed programatically. Also, you can't forget the $parent
in the ng-model because the ng-repeat
creates a new scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With