使用 ng-repeat 时默认选中单选按钮 [英] Radio button checked by default when using ng-repeat

查看:20
本文介绍了使用 ng-repeat 时默认选中单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直希望使用 ng-repeat 从屏幕上显示的单选按钮列表中检查一个单选按钮,但我的代码不起作用.这就是我正在做的事情:

I have been wanting to have a radio button checked out of a list of radio buttons that I present in the screen using ng-repeat, but my code does not work. This is what I am doing:

<div class="clubRole" data-ng-if="club.checked">
    <div data-ng-repeat="role in securityGroups.slice(0,1)">
        <input type="radio" class="clubRole" data-ng-model="club.role" data-ng-value="role.securityGroupCode" checked="checked"> {{role.description}}
    </div>
    <div data-ng-repeat="role in securityGroups.slice(1,securityGroups.length+1)">
        <input type="radio" class="clubRole" data-ng-model="club.role" data-ng-value="role.securityGroupCode"> {{role.description}}
    </div>      
</div>

代码的目的是让第一个单选按钮被选中,而其他的不被选中.该代码有一个问题:它不起作用.但至少它给出了我想要做的事情的想法:我希望默认选中其中一个单选按钮,无论它是哪一个.

The intention of the code is to get the first radio button checked, and the others unchecked. That code has a problem: it does not work. But at least it gives the idea of what I am trying to do: I want one of the radio buttons checked by default, no matter which one it is.

推荐答案

单选按钮将检查输入属性的值是否等于单选按钮上应用的模态值.

Radio button will be check if the value of the input attribute is equal to the value of modal applied on the radio button.

 <div ng-repeat="val in ['a','b','c']">
     <input
            type="radio"
            name="val"
            data-ng-model="role" 
            data-ng-value="val"
            ng-init="$index==0?(role=val):''"
      />
     {{val}}
 </div>

Checked="checked" 在角度上下文中不起作用.您可以在控制器中显式设置单选按钮的值,也可以像我在上面的示例中那样在视图本身中对其进行管理.但是根据输入元素上的 value 属性,模态应该是相等的.

Checked="checked" will not work in angular context. You can either set the value of radio button explicitly in controller or you can manage it in the view itself as i did in the above example.But the modal should be equate according to the value attribute on the inmput element.

例如,如果模态在三个单选按钮上为 x,并且每个单选按钮具有不同的值,例如 a、b 和 c.那么 x 必须等于要检查的任何值.

For example if modal is x on three radio button's and each radio button have different value like a,b and c. then x must be equal to any of the value to be checked.

Plunker

这篇关于使用 ng-repeat 时默认选中单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆