我在尝试使用ng-repeat
时设置默认选中的单选按钮。以下代码与我合作:
<div class="btn-group pull-right" id="dbHandle" data-toggle="buttons">
<label ng-repeat="handle in handles" for="" class="btn btn-primary">
<input type="radio" name="dbHandle" value="{{handle.handle}}" autocomplete="off">
{{handle.name}}
</label>
</div>
我希望在页面加载时检查第一个handle
。我已尝试在input
元素上使用以下三元组,但无效:
ng-checked="$index === 0 ? true : false"
答案 0 :(得分:4)
在您的输入上使用ng-model
:
<div class="btn-group pull-right" id="dbHandle" data-toggle="buttons">
<label ng-repeat="handle in handles" for="" class="btn btn-primary">
<input type="radio" name="dbHandle" value="{{handle.handle}}" ng-model="selectedOption" autocomplete="off">
{{handle.name}}
</label>
</div>
然后,将绑定值设置为您选择的句柄:
$scope.selectedOption = handles[0].handle;
// Or:
$scope.selectedOption = 2;
Angular将自动检查正确的元素:
angular.module('myApp', [])
.controller('myController', ['$scope',
function($scope) {
$scope.handles = [
{ handle: 0, name: 'Zero' },
{ handle: 1, name: 'One' },
{ handle: 2, name: 'Two' },
{ handle: 3, name: 'Three' }
];
$scope.selectedOption = $scope.handles[2].handle;
}
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<form ng-controller="myController">
<label ng-repeat="handle in handles" for="" class="btn btn-primary">
<input type="radio" name="dbHandle" value="{{handle.handle}}" ng-model="selectedOption" autocomplete="off">{{handle.name}}
</label>
</form>
</body>
&#13;