Using AngularJS to Create Dynamic Radio buttons through ng-repeat

I have a group of radio buttons that are generated using an ng-repeat directive, following the guidance provided in this helpful answer. However, I am struggling to understand how to integrate an ng-model into this setup.

   <tr ng-repeat="service in selectservice.services track by $index">
          <td>
            <input type="radio" name="serviceSelections" ng-value="{{service.name}}" id="service{{service.name}}">
          </td>
          <td>
            <h3>
              {{service.name}}
            </h3>
            <p>{{service.caption}}</p>
          </td>
        </tr>

This is the related controller code:

(function() {
  'use strict';

  angular.module('pb.ds.selectservice').controller('SelectServiceController', function($log) {
    var _this = this;

    _this.selectedService = 0;

    _this.services = [
      {
        selected: false,
        name: 'Postmates',
        caption: 'Guaranteed delivery within time'
      },
      {
        selected: true,
        name: 'Deliv',
        caption: 'Guaranteed delivery within time',
      },
      {
        selected: false,
        name: 'Roadie',
        caption: 'Guaranteed delivery within time',
      }
    ];
  });
})();

In the routing configuration for this view:

        content: {
          controller: 'SelectServiceController as selectservice',
          templateUrl: 'modules/select-service/templates/select-service.html'
        },

Currently, the radio button group correctly displays the second option as selected. However, I'm unsure about how to update the model and what exactly constitutes the model. I have attempted to use

ng-model="selectservice.selectedService"
, which should be assigned the value of 0, but in doing so, no radio button remains selected.

Answer №1

To properly assign the radio button group in your controller, you need to have a model and set it as ng-model. In this case, use the following code:

    _this.selectedService = "";

This will allow you to retrieve the name of the selected service.

To ensure functionality, adjust your HTML like so:

<tr ng-repeat="service in selectservice.services track by $index">
          <td>
            <input type="radio" ng-model="selectservice.selectedService" value="{{service.name}}" id="service{{service.name}}">
          </td>
          <td>
              {{service.name}}
            <p>{{service.caption}}</p>
          </td>
      </tr>

Once implemented, selecting any button will update _this.selectedService with the corresponding name. For example, choosing "Deliv" will update _this.selectedService with "Deliv". I hope this clarifies your query.

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

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Is it possible to link fields with varying titles in NestJS?

Currently, I am developing a NestJS application that interacts with SAP (among other external applications). Unfortunately, SAP has very specific field name requirements. In some instances, I need to send over 70 fields with names that adhere to SAP's ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Retrieve information from the server (using asp.net) using Java Script and store it in the local storage of the client device

I am receiving a JSON object from the server-side, but I have been struggling to save it in LocalStorage. When I check FireBug, this is how it appears: If you are having trouble viewing the images clearly, try opening them in a separate page by right-click ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...

Utilizing AngularJS's ng-repeat directive to iterate over an array stored in a $

My controller successfully retrieves and pushes an object onto an array using Parse: var mySite = angular.module('mySite', []); mySite.controller('listConnectors', ['$scope', function ($scope) { //Parse.initializ ...

I'm having trouble getting my ms-auto to properly align the contents within a div

I've been trying to use the ms-auto class in my code, but it doesn't seem to be working properly: <div class="p-5 rounded bg-light text-dark"> <div class="container row"> <div class="col-sm-6"> ...

Is there a way for me to iterate through an array of objects within a Redux reducer file in order to remove a specific user?

I am facing a challenge while trying to remove a user in redux. The issue arises when I use the map function in the reducer.js file and encounter a 'state.users.map is not a function' error. Upon investigation, I realized that the array consists ...

This code encountered an Uncaught SyntaxError due to an invalid or unexpected token

Hey there, I've been struggling with an Uncaught SyntaxError: Invalid or unexpected token issue whenever I try to click on the edit or delete button. Can someone please help me figure out what's wrong with this code? I've spent hours looking ...

Why is it beneficial to include multiple script blocks on a webpage?

Note: After reviewing the feedback from Andrew Moore, it seems that this question is a duplicate of Two separate script tags for Google Analytics?. Therefore, there may be merit in removing this question to prevent clutter on Stack Overflow. However, if th ...

Get a document from a NodeJS Server with the help of Express

How can I improve my file downloading functionality in Node.js? Currently, when I try to download a PDF file from the server, the content is displayed as data instead of initiating the download process. I would like it to function similar to how it's ...

Determine whether the element is visible in at least half of the viewport

I am working on a project that involves 4 cards with images. I want the image to animate in from the left when it comes into viewport. I have finalized the CSS for this effect, but the JavaScript code always returns false even when the element is visible o ...

Issues with npm installation on Ubuntu 16.04

Encountering issues while attempting to install npm on Ubuntu 16.04 using the command sudo apt-get install npm. The errors received are as follows: The following packages have unmet dependencies: npm : Depends: nodejs but it is not going to be installed ...

The visibility of the Google +1 button is lost during the partial postback process in ASP.NET

When trying to implement the Google Plus One button using AddThis on one of our localized pages, we encountered a strange issue. Despite retrieving data from the backend (let's assume a database), the plus button was not loading during an AJAX based p ...

The light/dark mode toggle is a one-time use feature

I've been experimenting with creating a button to toggle between light and dark modes on my website. Initially, it's set to light mode, but when I try switching to dark mode, it works fine. However, the issue arises when attempting to switch back ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

What could be the reason for the image not showing up on react?

When I try to retrieve the base64 image from the server, it is not displaying properly. Here is the error message I am getting: GET data:image/png;base64,{base64 string} net::ERR_INVALID_URL <img src={data?.gameIcon} alt="" className={st ...

Discover the process of integrating PWA features into an Express web application

I'm currently in the process of integrating PWA into a web application. I've created a manifest.json file and added it to the head of my page, which is loading correctly. However, the service worker registered in my app.js doesn't seem to be ...

Modifying the color of an SVG in real-time and using it as a texture in Three.js

I have been attempting to develop a configurator using three.js, but I am currently stuck at the stage where I need to dynamically change the color of the product. My initial idea was to use an SVG as a texture, modify the fill property of the SVG, and eas ...

The Impact of Spaces in Inline Scripting within Asp.NET

As I was coding in JavaScript on an Asp.NET page today, I encountered a small issue. Here's what happened: <script type="type/javascript"> var elementID = document.getElementById("<%=txtMyServerControl.ClientID %>") </script> T ...