AngularJS - 如果没有为单选按钮选择值,则设置默认值

时间:2015-02-04 21:29:54

标签: angularjs radio-button

我有以下一组单选按钮:

<div class="checkboxgroup" ng-repeat="p in priorities">
   <input id="radio_{{ $index }}" ng-disabled="disable" type="radio" name="ShipPriority" ng-model="$parent.data.ShipPriority" value="{{ p.value }}" ng-change="UpdateHeader('ShipPriority', {{ p.value }})" />
   <label for="radio_{{ $index }}">{{ p.value }}</label>
</div>

值/标签是数字1-5。由于它现在已设置,如果之前未选择任何值,则没有默认值,因此根本没有选择单选按钮。如果尚未选择先前的值,我想将默认值设置为5。

1 个答案:

答案 0 :(得分:2)

一种方法是仅使用ng-checked=""指令。

因此,您使用类似

的表达式添加ng-checked属性
ng-checked="$index == 1"

所以,如果要将第5个单选按钮($index = 4)设置为选中,则ng-repeat中的单选按钮将如下所示:

<input id="radio_{{ $index }}" ng-disabled="disable" 
    type="radio" name="ShipPriority" 
    ng-model="$parent.data.ShipPriority" value="{{ p.value }}" 
    ng-change="UpdateHeader('ShipPriority', {{ p.value }})"
    ng-checked="$index == 4"
/>

另一种方法是从优先级数组中获取已检查的值。

因此,您在控制器中设置优先级检查值,如下所示:

$scope.priorities = [{"value":1},{"value":2, "checked":true}];

并在视图中使用该值:

ng-checked="p.checked"

另一种方法是使用jQuery

$( document ).ready(function() {
    $("#radio_4").attr('checked', true);
});