0

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"
1
  • Try ng-checked='$first' on radio Commented Oct 14, 2015 at 13:59

1 Answer 1

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" 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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.