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

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

问题描述

在使用下列code。使用ngRepeat,3双单选按钮可以创建:

 < D​​IV NG重复=我在[1,2,3]>
    <输入类型=电台NAME =单选{{我}}ID =radioA {{我}}值=A选中>一个
    <输入类型=电台NAME =单选{{我}}ID =radioB {{我}}VALUE =B>乙
< / DIV>

由于某些原因,只有最后一对由ngRepeat产生的单选按钮是由影响检查属性。

这是因为这样的AngularJS更新有何看法?有没有办法解决?


解决方案

这可能是因为,当浏览器呈现单选按钮(如NG重复扩展)所有的收音机有即的名称相同的名称= 单选{{我}}角还没有扩大它,因此检查属性并不在所有的人都正确应用。所以,你需要使用<一个href=\"https://docs.angularjs.org/guide/directive#-ngattr-attribute-bindings\"><$c$c>ng-attr-name使角后增加了扩展名属性,这样尝试: -

 &LT; D​​IV NG重复=我在[1,2,3]&GT;
    &LT;输入类型=电台NG-属性名称=单选{{我}}NG-ATTR-ID =radioA {{我}}值=A选中&GT;一个
    &LT;输入类型=电台NG-属性名称=单选{{我}}NG-ATTR-ID =radioB {{我}}VALUE =B&GT;乙
&LT; / DIV&GT;

或者使用 NG-检查=真 ,以便检查属性应用于NG-检查指令扩展。即例如

 &LT;输入类型=电台NAME =单选{{I}}NG-ATTR-ID =radioA {{I}}值=ANG -checked =真正的&GT;一个

\r
\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
&LT; D​​IV NG-应用&GT;\r
\r
  \r
  &LT; D​​IV NG重复=我在[1,2,3]&GT;\r
    &LT;输入类型=电台NG-属性名称=单选{{我}}NG-ATTR-ID =radioA {{我}}值=A选中&GT;一个\r
    &LT;输入类型=电台NG-属性名称=单选{{我}}NG-ATTR-ID =radioB {{我}}VALUE =B&GT;乙\r
&LT; / DIV&GT;\r
&LT; / DIV&GT;

\r

\r
\r

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>

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

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

解决方案

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>

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天全站免登陆