Creating dynamic radio buttons in AngularJS

How can I create dynamic radio buttons in angularjs, using mobile numbers from this json array?

challengeSelectInfo:
[
    {"mob_0" : "xxxxx1211"},
    {"mob_1" : "xxxxx1211"},
    {"mob_2" : "xxxxx1211"}
]

I attempted to use ng-repeat and loop through challengeSelectInfo, but the challenge I'm encountering is that the keys (mob_0, mob_1, mob_2) are different. This causes difficulty in generating dynamic radio buttons.

Any assistance would be greatly appreciated.

Thank you!

Answer №1

Make sure to define keys for your arrays:

$scope.updatedArr = [];
angular.forEach(infoSelection, function(value, index) {
    /* perform action on each index: value pair */
     $scope.updatedArr.push({label: index, data: value});
});

Next, iterate through updatedArr arrays and set values for radio buttons:

<input name="{{choice.data}}" type="radio" ng-model="choice.label" value="{{choice.data}}">

Answer №2

created this for easier comprehension; hoping it helps you achieve your desired outcome

  var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.challengeSelectInfo= [
    {"mob_0" : "xxxxx1211"},

{"mob_1" : "xxxxx1211"},

{"mob_2" : "xxxxx1211"} ];


});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17767970627b7665397d6457263923396f">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   <div ng-repeat="(k,v) in challengeSelectInfo ">
     <div ng-repeat="(x,y) in v">
      <input type="radio" />{{y}}
     </div>
   </div>
   </body>
  

</html>

Answer №3

Could you please review this JSFIDDLE Demo


var information = { 
  "selectionDetails": [ {"item1": "xxxxx1211"},
                        {"item2": "xxxxx1211"}, 
                        {"item3": "xxxxx1211"} ]}

$scope.radioGroup = (information['selectionDetails'] || []).map(function(object){      
    for(var index in object){
        return { 'value': index, 'name': object[index] };
    }
});

<input type="radio" ng-repeat="rb in radioGroup" ng-value="rb.value" ng-model="radioValue" name="{{rb.name}}">

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

Restrict dropping items in HTML5 by only allowing the drop if the target div is

I am working on developing a user-friendly visual interface for creating simple graphics. The interface includes 10 image icons and 5 boxes where users can place these icons. Users have the freedom to select which icon they want to display and arrange them ...

Node and Web scraping Promise: a powerful combination

I've been using Cheerio and Node for web scraping, and I thought implementing promises could simplify handling asynchronous code. However, my attempt to chain promises hasn't been successful. Below is the code I'm working with, in hopes that ...

After a period of 10 minutes with no activity, proceed to the next page

I am in the process of developing a custom local website that will be displayed on a large touch screen at my current workplace. Only one user can interact with it at a time. My client has requested a screensaver feature to appear after 10 minutes of no i ...

I noticed that when I use jQuery to add a class to an <li> element, the class is added successfully but then quickly removed. I'm wondering if this could be a conflict with

$(document).ready(function() { var $listItems = $('ul li'); listItems.click(function() { $listItems.removeClass('selected'); $(this).addClass('selected'); }); }); .selected{ background color: "green"; } / ...

Vue alert: Issue with rendering - TypeError: Unable to access property 'NomeStr' as it is undefined

I'm having trouble displaying the 'NameSrt' item array value in my template, and I keep encountering this issue: vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'NomeStr' of undefined" The ...

Conceal image and substitute with a different image using JavaScript

My query pertains to JavaScript: how can I create an effect where clicking the jump-down button opens a text box and causes the button to change direction and rotate? I am considering using two photos - one hides when the jump-down button is clicked, and ...

What causes the inversion of height and width settings in react-webcam?

Currently utilizing react-webcam with the following configuration. <Webcam audio={false} screenshotFormat="image/jpeg" videoConstraints={{ facingMode: "environment", width: camera ...

What is the best way to encapsulate a function that uses `this.item.findElement()` from Selenium in a separate file?

I'm currently working on setting up a Selenium Webdriver and Cucumber.js test environment using Node.js. In the homePageSteps.js file, I have a check to verify if a banner exists on a page: Then('there should be a banner', async function() ...

Switching Image Values in JavaScript: A Quick Guide

After successfully using a JavaScript function to swap the src of two images, I encountered an issue. I also needed to switch two values associated with the images so that I could calculate them later. For example: img src="ble.jpg" id="F" value="" onclic ...

Is there a gentle approach to transferring calendar event variables in JavaScript?

The example provided below showcases a @model that contains data. To utilize specific portions of the data, I have transformed it into a Json object using Json.Serialize. This was necessary because the events:[ ] section requires data in a particular form ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...

Ways to troubleshoot and fix the problem of encountering an "Internal Server Error" when sending emails with nodeMailer in node.js

When attempting to send a confirmation email using nodemailer, I encountered an internet server error in production when allowing insecure apps for Gmail accounts, although it works fine locally. Any suggestions on how to resolve this issue? router.post(& ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Display/Conceal a div using CSS in React JS/Redux

I've been working on a CSS toggle for a div with className toggling. My approach involves using redux to manage the boolean state. Using the redux chrome extension, I can see that the state is indeed changing but the div remains invisible. If you have ...

Creating a recursive setTimeout loop using Coffeescript

I am currently developing a live photo stream application. The idea is that users will be able to upload photos to a specific folder on my server via FTP, and the app should automatically update whenever a new photo is added, without needing to refresh the ...

Node.js dynamically updates exports for efficient code execution

I am facing an issue with exporting and importing an object in my code. The object starts off empty but gets populated with keys and values when a button is clicked. However, when other files import this object, it still shows as empty. How can I dynamical ...

NPM encountered an issue that prevented it from scanning directories due to a permission denial with the error code E

Whenever I type "npm run build:prod" build:prod npm run build -- --configuration production --aot --optimization=false I encounter the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e4e3ece1fbafece3 ...

Learn how to easily modify a value in a CVS file by simply clicking on the data point on a highcharts graph

Is there a way to update my CSV file by clicking on a graph? I want to be able to create a graph from data in the same CSV file and then, when I click on a point, set that point to zero on the y-axis and update the corresponding value in the CSV file to 0. ...

Model of Objects within a Document

Here's a puzzling question for you: why does console.log(document.body) and console.log(document.head) work perfectly fine, but console.log(document.script) or console.log(document.html) don't seem to do anything? It's strange because all of ...