AngularJS ng-repeat issue: Radio buttons not working as expected

I attempted to create a dynamic form with radio buttons, but I am facing issues in getting the form to function properly.

Here is my code:

<tr ng-repeat="i in [1,2,3] track by $index">
  <td><input type="text" class="form-control"></td>
  <td>
    <label>
        <input ng-model="$parent.reservation.gender" type="radio"
               name="gender.$index"
               value="male" checked>
        Male
    </label>

    <label>
        <input ng-model="$parent.reservation.gender" type="radio"
               name="gender.$index"
               value="female" checked>
        Female
    </label>
  </td>
  <td><input type="text" class="form-control"></td>
</tr>

In my situation, I need to select the gender for each row, but I am struggling to configure the parameters correctly to make it work.

View a screenshot of my work here

Access the Plunkr link for this issue

Answer №1

Your explanation is a bit vague about what exactly "running correctly" entails, so I will make an educated guess.

It seems like you are trying to create a reservation object that contains information for multiple people within the scope of an ng-repeat. Essentially, if you were to have a controller named ReservationCtrl, it should look something like this:

$scope.reservation = 
  [
    {name: "Alice", gender: "female", age: 25},
    {name: "Bob", gender: "male", age: 30},
    // and so on...
  ];

To achieve this, you can define the following controller:

app.controller("ReservationCtrl", function($scope){
  $scope.reservation = [{}]; // initializing with one empty person
  $scope.addPerson = function(){ $scope.reservation.push({}); }
});

Now, in your HTML view:

<div ng-repeat="person in reservation">
  <input ng-model="person.name" type="text">
  <label>Male:   
     <input ng-model="person.gender" name="gender{{$index}}" type="radio" value="male">
  </label>
  <label>Female: 
     <input ng-model="person.gender" name="gender{{$index}}" type="radio" value="female">
  </label>
  <input ng-model="person.age" type="number">
</div>
<button ng-click="addPerson()">Add another person</button>

You can also check out this example on Plunker.

Answer №2

Avoid using the checked attribute. Make sure to initialize your model with a value so that it is automatically checked:

<tr ng-repeat="item in [1,2,3] track by $index" ng-init="$parent.user.gender='female'">

Additionally, you probably meant to use name="gender.{{$index}}" instead of name="gender.$index"

http://plnkr.co/edit/X8YXa5n5gLkjXOTTB7RL?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for some guidance on grasping the concept of strict mode in React and determining what actions can be considered side effects

The other day, I came across a strange bug in React and here is a simplified version of it. let count = 0; export default function App() { const [countState, setCountState] = useState(count); const [countState2, setCountState2] = useState(count); con ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Bidirectional data binding in Angular 2 for the class attribute

Utilizing twitter bootstrap tabs, I aim to monitor the application of the active class on the li tag as users switch between different tabs. My objective is to control tab activation through custom buttons by modifying the class attribute to activate direc ...

Is there a way to prevent Material-UI SpeedDial from automatically closing when a SpeedDialAction button is clicked?

Looking to customize the functionality of Material-UI's SpeedDial component (https://material-ui.com/api/speed-dial/). At present, when a SpeedDialAction is clicked, the main SpeedDial component automatically closes. I want to modify this behavior s ...

Removing an element from a list using Angular 2 by simply clicking with the mouse

I'm encountering a small issue with my code. I've developed a weather application using Angular 2 and it's functioning well. However, I'm facing a problem when clicking the "delete this city" button - it only deletes the last city inste ...

I am having trouble getting text to display properly in a jQuery Mobile dialog

I am attempting to dynamically set the header and button texts using JavaScript, but unfortunately it's not working as expected. To demonstrate the issue, I have added my code on jsfiddle: http://jsfiddle.net/tMKD3/8/. Here is the HTML code: <bod ...

A step-by-step guide on utilizing img src to navigate and upload images

I would like to hide the input type='file' element with id "imgInp" that accepts image files from users. Instead, I want them to use an img tag to select images when they click on a specific img tag. How can this be achieved using jQuery? Here i ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

Is it possible for jquery.find() to only target immediate children?

How can I use jQuery.find() to specifically target only the direct children of an element without selecting their descendants? Leading the selector with '>' or using '*' doesn't give me the desired result. While I know about jQ ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Angular-nvd3: maintaining consistent spacing between data points along the x-axis

By default, the scale of the x-axis is calculated from values, resulting in uneven distances between two adjacent points. For example, with an array of values like [1,2,5], there will be different distances on the x-axis for each point, and the x-axis labe ...

Using JavaScript and jQuery to calculate the time difference between two values

Here is a code snippet for calculating the difference between two numbers: function calculateDifference(num1, num2) { if (num1 > num2) { return num1 - num2; } else { return num2 - num1; } } On document.ready event: var result = calculateD ...

React Native: Changing Props Triggers Touch Event Cancellation

I am currently utilizing the react-native-gesture-handler library to construct a drag-and-drop sortable array of components. As I progress in the development, I am now focusing on incorporating animations into the functionality. To achieve this, I utilize ...

Displaying a Modal with a Click Action

I am encountering a challenge in displaying a modal when clicked using onClick(). In a component, I have a function that adds players to a list when the Add Player button is clicked. This button is generated separately in a function called renderAddButton( ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

Is it possible for the outcome of a component to be passed to render and actually show up as undefined

I am currently working on creating a wrapper component for an API call in order to display "loading" if the API hasn't updated yet. As I am new to React, I am struggling with passing the state to the ApiResp component: After checking the console.log ...

Using javascript to transform the entire list item into a clickable link

Currently, I am using PHP in WordPress CMS to populate slides on a slider. Each slide contains a link at the bottom, and my goal is to target each slide (li) so that when clicked anywhere inside it, the user is directed to the URL specified within that par ...

Tips for displaying a specific PDF file using the selected programming language

As a newcomer to react.js, I have a question regarding my system which allows the user to select the default language. If the chosen language is French, there is a specific URL that needs to be included in the Iframe path. For Spanish, it's a specific ...

Can you show me how to condense this using the ternary operator?

Although I don't necessarily have to refactor this code, I am intrigued by the idea of doing so. handleError: ({ error, email, password }, props) => authError => { if (email === "" || password === "") { return { error: `Plea ...

Challenges with loading content and async JavaScript within websites

I decided to replace the content on index.htm with the content from project.htm. By clicking on a#front, it redirects to project.htm and dynamically updates the content. However, I am facing an issue regarding how to run the javascript that accompanies thi ...