Reputation: 3616
I'm attempting to set the default checked radio button while using ng-repeat
. The below code is what I'm working with:
<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>
I would like for the first handle
to be checked on page load. I've tried using the following ternary on the input
element, but to no effect:
ng-checked="$index === 0 ? true : false"
Upvotes: 0
Views: 7044
Reputation: 72957
Use ng-model
on your inputs:
<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>
Then, set the bound value to the handle of your choice:
$scope.selectedOption = handles[0].handle;
// Or:
$scope.selectedOption = 2;
Angular will automatically check the correct element:
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;
}
]);
<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>
Upvotes: 4