admin管理员组

文章数量:1418964

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}}" autoplete="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"

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}}" autoplete="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"
Share Improve this question asked Oct 14, 2015 at 13:55 MattDionisMattDionis 3,62610 gold badges55 silver badges111 bronze badges 1
  • Try ng-checked='$first' on radio – Tushar Commented Oct 14, 2015 at 13:59
Add a ment  | 

1 Answer 1

Reset to default 4

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" autoplete="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./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" autoplete="off">{{handle.name}}
    </label>
  </form>
</body>

本文标签: javascriptHow to set default checked radio button in AngularStack Overflow