在AngularJS中设置单选按钮checked = true的方式有什么区别 [英] What is difference in ways of setting radio button checked=true in AngularJS
问题描述
如果我使用 ng-checked ="$ first"
设置单选按钮默认选择,则它被选中.如果我使用 ng-checked ="true"
单选按钮未选中?
If I set radio button default selection using ng-checked="$first"
then it got checked. If I use ng-checked="true"
radio button doesn't get checked?
请解释何时会发生这种情况?
Kindly explain when this can happen?
我无法在用例中使用 $ first
acc
I cant use $first
acc to my Use case
推荐答案
单选按钮一旦选中即无法取消,要注意的一件事.您必须提供其他选择.我为您准备了一些样品.
One thing to note about radio buttons once you check they cant be unchecked. You must have to provide another options. I prepared some samples for you.
在第一种方法中,尽管我在控制器中将值设置为true并将值设置为1,但仍进行了检查.这是最佳的解决方案.
In 1st method eventhough i set the value to true in controller and set the value to 1 it got checked.this is the most optimal solution.
使用ng-checked的第二种方法,即使我更改了值,但ng-model的值也未更新.因此您必须使用ng-change函数并跟踪每个ng-model.个人没人喜欢这种方法.
2nd method using ng-checked eventhough i change the value but ng-model values are not updated. so you have to use ng-change function and track every ng-model.personally nobody like this method.
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.myradio = true;
$scope.myradio_ng1 = true;
$scope.myradio_ng2 = false;
$scope.first = true; // probably you are getting this from db
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Radio</title>
</head>
<body ng-controller="MainCtrl">
<p>1. Using ng-model</p>
<div>
<label for="myradio1">Yes</label>
<input type="radio" ng-model="myradio" name="myradio" id="myradio1" value="1" />
<label for="myradio2">No</label>
<input type="radio" ng-model="myradio" name="myradio" id="myradio2" value="0"/>
</div>
<div>Radio value: {{myradio}}</div>
<p>2. Using ng-checked</p>
<div>
<label for="myradio3">First</label>
<input type="radio" name="myradiong" id="myradio3" ng-checked="myradio_ng1" />
<label for="myradio4">Second</label>
<input type="radio" name="myradiong" id="myradio4" ng-checked="myradio_ng2"/>
<div>Radio value for first: {{myradio_ng1}}</div>
<div>Radio value for Second: {{myradio_ng2}}</div>
</div>
<p>Your case</p>
<label for="first">First</label>
<input type="radio" id="first" ng-checked="first" />
</body>
</html>
在您的情况下,您有一个要检查的元素为真.在您的控制器中,将 $ scope.first
的值设置为true或false,然后在您的视图中使用 ng-checked ="first"
.通过运行代码片段查找结果.
In your case you have an element you want to checked when it is true. In your controller set the value of $scope.first
to true or false then in your view use ng-checked="first"
. Find the result by running the code snippet.
这篇关于在AngularJS中设置单选按钮checked = true的方式有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!