如果我使用ng-checked="$first"
设置单选按钮默认选择,则会检查它。如果我使用ng-checked="true"
单选按钮未检查?
请说明何时会发生这种情况?
我无法使用$first
acc来使用我的用例
答案 0 :(得分:0)
关于单选按钮,有一点需要注意,一旦你检查它们就不能取消选中。您必须提供其他选项。我为你准备了一些样品。
在第一种方法中,虽然我在控制器中将值设置为true并将值设置为1,但它已被检查。这是最佳解决方案。
使用ng-checked事件的第二种方法尽管我改变了值但是ng-model值没有更新。所以你必须使用ng-change功能并跟踪每个ng-model。个人没有人喜欢这种方法。
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>
&#13;
在您的情况下,如果确实存在要检查的元素。在控制器中将$scope.first
的值设置为true或false,然后在视图中使用ng-checked="first"
。通过运行代码段找到结果。