AngularJS,ngRepeat,并默认选中的单选按钮单选、按钮、AngularJS、ngRepeat

2023-09-13 03:05:24 作者:独纵

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

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

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

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

解决方案 angularjs如何遍历数组

这可能是因为,当浏览器呈现单选按钮(如NG重复扩展)所有的收音机有即的名称相同的名称= 单选{{我}}角还没有扩大它,因此检查属性并不在所有的人都正确应用。所以,你需要使用ng-attr-name使角后增加了扩展名属性,这样尝试: -

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

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

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

\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>