AngularJS、ngRepeat 和默认选中的单选按钮 [英] AngularJS, ngRepeat, and default checked radio button
问题描述
使用 ngRepeat 时,可以使用以下代码创建 3 对单选按钮:
<input type="radio" name="radio{{i}}" id="radioA{{i}}" value="A" 选中>一种<input type="radio" name="radio{{i}}" id="radioB{{i}}" value="B">乙
出于某种原因,只有 ngRepeat 生成的最后一对单选按钮受到 checked
属性的影响.
这是因为 AngularJS 更新视图的方式吗?有办法解决吗?
这可能是因为当浏览器呈现单选按钮时(随着 ng-repeat 展开)所有的单选按钮都具有相同的名称,即 "name="radio{{i}}"
angular 还没有扩展它,因此所有的检查属性都没有正确应用.所以你需要使用 ng-attr-name
以便 angular 稍后添加扩展名称属性.所以尝试:-
<input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" 选中>一种<input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B">乙
或者使用ng-checked="true"
以便在 ng-checked 指令扩展时应用 checked 属性.即示例
<input type="radio" name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" ng-checked="true">一种
<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" 选中>一种<input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B">乙
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屋!