如何在Angular中设置默认的选中单选按钮

How to set default checked radio button in Angular

本文关键字:单选按钮 默认 设置 Angular      更新时间:2023-09-26

我试图在使用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"

在输入中使用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;
  }
]);
<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>