问题描述
在angularjs
的开发中,我们有时候可能会使用ng-repeat
指令动态生成一系列的单选框radio
集合,如下:
<li ng-repeat="person in people">
<label>{{person.name}}
<input type="radio" name="name" required="required"/>
</label>
</li>
那么,在angularjs
的开发中,我们如何设置这个由ng-repeat
动态生成的单选框列表的默认选中项呢?
方案一
使用ng-model
与radio
的value
值一致原则来选中默认的单选项,如下:
HTML:
<div ng-controller="MyCtrl">
<section id="section_1">
<p>Favorite Beatle:</p>
<ul>
<li ng-repeat="person in people">
<label>{{person.name}}
<input type="radio" ng-model="$parent.favoriteBeatle"
name="name" value="{{person.name}}" required="required"/>
</label>
</li>
</ul>
<p>Your favorite Beatle is <strong>{{favoriteBeatle}}</strong>.</p>
</section>
</div>
Angular.js:
function MyCtrl($scope) {
$scope.people = [{
name: "John"
}, {
name: "Paul"
}, {
name: "George"
}, {
name: "Ringo"
}];
$scope.favoriteBeatle = 'Paul';
setTimeout(function () {
$('input[value=George]').trigger('click');
}, 2000);
setTimeout(function () {
$('input[value=George]').trigger('click');
}, 4000);
}
方案二
使用ng-checked
即可,如下:
HTML:
<div ng-controller="MyCtrl">
<section id="section_2">
<p>Favorite color:</p>
<ul>
<li ng-repeat="color in colors">
<label>{{color.name}}
<input type="radio" ng-checked="(favoriteColor==color.name)"
name="color" ng-click="handleFavoriteColor(color)" ng-value="{{color.name}}" required="required"/>
</label>
</li>
</ul>
<p>Your favorite color is <strong>{{favoriteColor}}</strong>.</p>
</section>
</div>
Angular.js:
function MyCtrl($scope) {
$scope.colors = [{
name: "Red"
}, {
name: "Green"
}, {
name: "Blue"
}, {
name: "Yellow"
}];
$scope.favoriteColor ='Blue';
$scope.handleFavoriteColor = function(color){
$scope.favoriteColor =color.name;
}
}