AngularJs radio buttons are connected when using ng-form with ng-repeat

三世轮回 提交于 2019-12-08 07:36:59

问题


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>

回答1:


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




回答2:


As per your last comment, I have tried this out and it works. I'm not using the built-in angular validation but I believe it works all the same and is very simple

    <li ng-repeat="item in items" ng-form="subForm">
      <input type="text" required name="name" ng-model="item.name"/>
      <input type="radio" value="r1" ng-model="item.radio" /> r1
      <input type="radio" value="r2" ng-model="item.radio" /> r2
      <span ng-show="item.radio==''">required</span>
      <button type="button" ng-disabled="subForm.$invalid || item.radio==''" ng-click="submitOne(item) ">Submit One</button>
    </li>

See my working example at http://wiredbeast.com/coolframework/stackover.html

The trick is using ng-show="item.radio==''" to show the validation error and to disable the "Submit One" button.

In my honest opinion angular form validation and browser validation with checkboxes and radios is not very solid.



来源:https://stackoverflow.com/questions/19114478/angularjs-radio-buttons-are-connected-when-using-ng-form-with-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!