I'm trying to bind a radio button to true when the radio button is selected and to false when the radio button is not selected. I must be missing something really obvious because I haven't been able to do it yet.
I have a simple collection, eg:
$scope.collection = [
{ id: 1, selected: true},
{ id: 2, selected: false},
{ id: 3, selected: false}];
And I wish to bind the "selected" property to whether the radio button is checked or not. Sounds simple enough but ng-model binds to undefined. ng-checked almost works, it displays the correct result but never actually updates the value...
You can bind the radio buttons to the right object fields in from the controller $scope
:
angular.module('ExampleApp', [])
.controller('ExampleCtrl', ['$scope', function ($scope) {
$scope.radioContent = [
{txt: 'One', checked: false},
{txt: 'Two', checked: false}
];
$scope.$watch('radioContent', function (now, then) {
console.debug('Something changed', now);
}, true);
}]);
And the HTML:
<div ng-app="ExampleApp" ng-controller="ExampleCtrl">
<div ng-repeat="radio in radioContent">
<input type="radio" ng-model="radio.checked">{{radio.txt}}
</div>
</div>
Here's a working Fiddle
Seems like ng-bind and ng-selected don't work that well with radio buttons, but if you change the radio buttons to be checkboxes, the code works as expected.
And using @Ashesh's answer, the radio.checked property of a button still becomes undefined after messing with the radio button once.
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*"
data-semver="1.3.0-beta.5"
src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script>
angular.module("sampleapp", [])
.controller('samplecontroller', function($scope,$rootScope) {
$scope.collection = [
{ id: 1, selected: true},
{ id: 2, selected: false},
{ id: 3, selected: false}];
});
</script>
</head>
<body ng-app="sampleapp" ng-controller="samplecontroller">
<div class="radio" ng-repeat="element in collection">
<span ng-bind="element.id"></span>
<span ng-bind="element.selected"></span>
<input type="checkbox" name="whatever" ng-model="element.selected">
</div>
</body>
</html>
However, if you change the selected property into true
or false
and NOT "true"
or "false"
, it works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.