如何使用angularJS检查单选按钮
How to check a radio button with angularJS?
我正在创建一个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
,它应该是true
或false
<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>
(我使用上一个答案中的代码)
相关文章:
- 如何设置第一个子元素's的单选按钮已在轨道上检查4
- vue-js-单选按钮won't默认情况下使用v-model属性进行检查
- html单选按钮检查问题
- JS中的单选按钮检查不起作用
- 更改单选按钮检查的值的字体大小
- Wooccommerce单选按钮检查jquery
- 通过单选按钮检查提交表单
- 对用户交互进行单选按钮检查
- 单选按钮检查属性在函数 - JavaScript 中失败
- 基于单选按钮检查值调用Javascript函数
- 单选按钮检查的属性未更改
- jQuery单选按钮检查操作不'不要开火
- knockoutjs单选按钮检查了protectedobservable的值
- 通过单选按钮检查值
- 依靠单选按钮检查
- Angularjs:当模型改变时,单选按钮检查状态绑定模型值失败
- jquery中的单选按钮检查选择更改事件
- 禁用基于单选按钮检查的必选字段验证器
- 如何在Javascript中更新基于单选按钮检查的选择框
- 用于单选按钮检查的JavaScript if语句