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

时间:2015-10-14 13:55:37

标签: javascript angularjs

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

1 个答案:

答案 0 :(得分:4)

在您的输入上使用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将自动检查正确的元素:

&#13;
&#13;
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;
  }
]);
&#13;
<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>
&#13;
&#13;
&#13;