如何使用angularJS检查单选按钮

How to check a radio button with angularJS?

本文关键字:单选按钮 检查 angularJS 何使用      更新时间:2024-02-19

我正在创建一个html/angularjs表单。在表单中,我有一个带有yes或no的单选按钮。所以我想默认选中按钮no。这是我使用的代码:我的控制器:

angular.module('radioExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.myvariable = 'false';
    }]);

我的html代码片段:

<div class="col-lg-10">
                <input type="radio" id="variable" name="variable" ng-model="myvariable" value="true">Yes</input> 
                <input type="radio" id="variable" name="variable" ng-model="myvariable" value="false">No</input>
            </div>

但当我第一次加载表单时,没有选择(选中)任何内容。我必须单击一个值才能选择一个(选中)我的代码出了什么问题?这里是plunker链接感谢

我为您制作了一个fiddle。查看此处

您还应该设置ng-value,它应该是truefalse

<div ng-controller="MyCtrl">
    <div ng-repeat="o in options">
        <input type="radio" name="group1" ng-model="o.checked" ng-value="o.checked"></input>
        <label>{{o.name}}</label>
    </div>
</div>

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
    $scope.options =  [
       { name: 'OPT1', id: 1, checked: false },
       { name: 'OPT2',id: 2, checked: false },
       { name: 'OPT3',id: 3, checked: true  }
    ];
   }

它在plunkr中不起作用的原因是您创建了一个名为"radioExample"的模块,但在编写HTML代码时没有使用它。

基本上,更换这个-

<html ng-app>

在这个代码的开头

<html ng-app="radioExample">

这样,当您声明控制器时,AngularJS就知道需要查看哪个模块才能获得控制器。

请注意,如果您没有将控制器与模块相关联,那么您的代码就会工作。

查看ng-checked。您要做的是将ng-app="radioExample"添加到应用程序的html-标记中。

然后添加ng-checked="myvariable == 'false'"ng-value="'value'",就像下面的plunker示例一样:Plunker

<div class="col-lg-10">
    <input ng-checked="myvariable == 'true'" type="radio" id="variable" name="variable" ng-model="myvariable" value="true">Yes
    <input ng-checked="myvariable == 'false'" type="radio" id="variable" name="variable" ng-model="myvariable" value="false">No
</div>

数据绑定错误。在单选按钮中的控制器覆盖值中定义myvariable。你必须像一样使用ng重复

<div ng-repeat="o in options">
    <input type="radio" name="name" ng-model="o.checked" ng-value="o.checked"></input>
    <label>{{o.name}}</label>
</div>

(我使用上一个答案中的代码)