AndreaM16
AndreaM16

Reputation: 3975

Multiple radio buttons inside multiple repeated items - AngularJS

I've a problem that I was't able to solve with other related SO Q/A.

This is my situation:

I'm able to see correctly every Item with its own buttons but I'm not able to select the right button on click.

When I click on a button outer than first Item's buttons, the event does not work properly, it triggers events on the first item.

I would like to achieve the same result as in this Plunker I just made.

Here is my original code:

Template that includes a Single Item Template per each Item:

<div class="myClass" ng-repeat="item in items">
  <div ng-include src="mySingleElement"></div>
</div>

Single Item Template That has multiple Radio Buttons:

<ul>
    <li ng-repeat = "button in survey.buttons">
        <input type="radio" id="radio_{{$parent.$index}}" 
               name="radio{{$parent.$index}}""/>

            <label for="radio_{{$parent.$index}}">
              <span></span>{{button.text}}
            </label>
     </li>
</ul>

Here are some images where I show the behaviour in my application:

Starter situation, e.g. with two items:

In the first item, I'm able to click only the first radio button, if I click on other buttons they always check the first one.

I'm able to click only the first radio button, if I click on others they won't work

Trying to interact with the second Item:

It happens the same thing as in the first one, same for all other items.

enter image description here

I don't really get why it does not work properly like in the Plunker. I made the Plunker with the exact same code but including single item's layout with ng-include in a separated file.

What Am I doing wrong and how can I solve this? Is it caused by the ng-include?

Upvotes: 1

Views: 996

Answers (1)

AGdev
AGdev

Reputation: 616

Problem seems to be that we are trying to use same radio buttons id while repeating for item1 to item n.Let say index start from 1.

For example

Item 1 -> radio_1,radio_2,radio_3....
Item 2 ->radio_1,radio_2,radio_3...
Item 3 ->radi0_1,radio_2,radio_3...

But To do it correctly we need to

Item 1 ->radio_1_1,radio_1_2,radio_1_3...
Item 2 ->radio_2_1,radio_2_2,radio_2_3.... 
Item 3 ->radio_3_1,radio_3_2,radio_3_3....

So we need get hold of item index from first ng repeat like this

<div class="myClass" ng-repeat="item in items" ng-init="outerIndex = $index">

Then 2 ng-repeat which will be nested inside first one will be

<ul>
<li ng-repeat = "button in survey.buttons" ng-init="innerIndex = $index">
    <input type="radio" id="radio_{{outerIndex}}_{{innerIndex}}" 
           name="radio{{outerIndex}}_{{innerIndex}}""/>

        <label for="radio_{{outerIndex}}_{{innerIndex}}">
          <span></span>{{button.text}}
        </label>
 </li>

Upvotes: 2

Related Questions