[英]Radio button ng-model to true/false (checked/unchecked)
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. 我正在尝试将单选按钮绑定到true(当选择了单选按钮时)和false(在未选择单选按钮时)。 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. 我希望将“ selected”属性绑定到是否选中单选按钮。 Sounds simple enough but ng-model binds to undefined.
听起来很简单,但是ng-model绑定到未定义。 ng-checked almost works, it displays the correct result but never actually updates the value...
ng-checked几乎可以使用,它显示正确的结果,但从未实际更新值...
You can bind the radio buttons to the right object fields in from the controller $scope
: 您可以将单选按钮绑定到控制器
$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: 和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>
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. 似乎ng-bind和ng-selected不适用于单选按钮,但是如果将单选按钮更改为复选框,代码将按预期工作。
And using @Ashesh's answer, the radio.checked property of a button still becomes undefined after messing with the radio button once. 使用@Ashesh的答案,一次将单选按钮弄乱后,按钮的radio.checked属性仍然变得不确定。
<!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. 但是,如果将选定的属性更改为
true
或false
而不是 "true"
或"false"
,则该属性有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.