简体   繁体   中英

How to set default checked radio button in Angular

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"

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM