2015-10-14 209 views
0

我正在嘗試設置默認選中單選按鈕,同時使用ng-repeat。下面的代碼就是我的工作:如何在Angular中設置默認選中單選按鈕

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

嘗試'NG-檢查='無線電$ first'' – Tushar

回答

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

相關問題