AngularJS、ngRepeat 和默认选中单选按钮 [英] AngularJS, ngRepeat, and default checked radio button

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

问题描述

使用 ngRepeat 时,可以使用以下代码创建 3 对单选按钮:

When using ngRepeat, 3 pairs of radio buttons can be created using the following code:

<div ng-repeat="i in [1,2,3]">
    <input type="radio" name="radio{{i}}" id="radioA{{i}}" value="A" checked> A
    <input type="radio" name="radio{{i}}" id="radioB{{i}}" value="B"> B
</div>

由于某种原因,只有 ngRepeat 生成的最后一对单选按钮受 checked 属性影响.

For some reason, only the last pair of radio buttons generated by ngRepeat is affected by the checked attribute.

这是因为 AngularJS 更新视图的方式吗?有办法解决吗?

Is this because of the way AngularJS updates the view? Is there a way to fix it?

推荐答案

这可能是因为当浏览器渲染单选按钮时(随着 ng-repeat 的扩展),所有单选按钮都具有相同的名称,即 "name="radio{{i}}" angular 还没有扩展它,因此选中的属性没有在所有这些中正确应用.所以你需要使用 ng-attr-name 以便 Angular 稍后添加扩展名称属性.所以尝试:-

That is possibly because when browser renders the radio buttons (as ng-repeat expands) all your radios have same name i.e "name="radio{{i}}" angular has not expanded it yet, hence the checked property is not applied properly among all of them. So you would need to use ng-attr-name so that angular adds expanded name attribute later. So try:-

<div ng-repeat="i in [1,2,3]">
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" checked> A
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B"> B
</div>

或使用 ng-checked="true" 以便在 ng-checked 指令扩展时应用检查属性.即示例

Or use ng-checked="true" so that checked attribute is applied as ng-checked directive expands. i.e example

<input type="radio" name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" ng-checked="true"> A

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>

  
  <div ng-repeat="i in [1,2,3]">
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" checked> A
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B"> B
</div>
</div>

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

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