AngularJs 单选按钮在使用 ng-form 和 ng-repeat 时连接 [英] AngularJs radio buttons are connected when using ng-form with ng-repeat
问题描述
看到这个 plnkr http://plnkr.co/edit/WZHMuYY3y2wbI6UysvY6?p=preview一个>
在包含单选按钮组的 ng-repeat 上使用 ng-form 标签时,单选按钮是链接的,因此如果您在一个 ng-repeat 中选中一个单选按钮,它将在所有其他 ng-repeat 中取消选择.这让我感到困惑,因为 ng-repeat 的模型与其他项目隔离开来.这不仅是使用 ng-repeat 时的问题.当具有独立范围的自定义指令的多个实例呈现
在 Plnkkr 中尝试添加一些项目并检查一些项目上的单选按钮.他们应该是独立的,但事实并非如此.
这是 Angular 中的错误吗?如果不是,为什么它会以这种方式工作,我该如何解决?
解决方案 这些单选按钮由浏览器连接",因为您为它们指定了相同的名称.只需删除 name
属性,事情就会开始按预期工作:http://plnkr.co/edit/AEtGstSBV6oydtvds52Y?p=preview
See this plnkr http://plnkr.co/edit/WZHMuYY3y2wbI6UysvY6?p=preview
When using a ng-form tag on an ng-repeat which contains a radio button group, the radio buttons are linked so if you check a radio button in one ng-repeat it will deselect in all the other ng-repeats. This puzzles me as the model of the ng-repeat is otherwise isolated from the other items. This is not only an issue when using ng-repeat. It also occurs when having multiple instances of a custom directive with isolated scope which renders a
<div ng-form name="myForm">
In the Plnkkr try adding a number of items and check the radio buttons on some of the items.
They should be independent, but they are not.
Is this a bug in Angular?
If not why does it work this way and how can I work around it?
<form name="mainForm" ng-submit="submitAll()">
<ul>
<li ng-repeat="item in items" ng-form="subForm">
<input type="text" required name="name" ng-model="item.name"/>
<input type="radio" name="myRadio" value="r1" ng-model="item.radio" /> r1
<input type="radio" name="myRadio" value="r2" ng-model="item.radio" /> r2
<span ng-show="subForm.name.$error.required">required</span>
<button type="button" ng-disabled="subForm.$invalid" ng-click="submitOne(item)">Submit One</button>
</li>
</ul>
<button type="submit" ng-disabled="mainForm.$invalid">Submit All</button>
</form>
解决方案 Those radio buttons are "connected" by a browser since you are giving them the same name. Just drop the name
attribute and things start to work as expected:
http://plnkr.co/edit/AEtGstSBV6oydtvds52Y?p=preview
这篇关于AngularJs 单选按钮在使用 ng-form 和 ng-repeat 时连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文