Tips for transferring chosen radio button to controller using AngularJS

Is there a way to use console.log() to output the selected radio button? I attempted to set a default selection with checked="checked", but it didn't function as expected.

<body ng-app="app">
  <div class="container"  ng-controller="radioController">
    <label for="redRadio">Red:</label>
    <input id="redRadio" type="radio" ng-model="colorValue" value="red" /><br />

    <label for="greenRadio">Green:</label>
    <input checked="checked" id="greenRadio" type="radio" ng-model="colorValue" value="green" /><br />

    <label for="blueRadio">Blue:</label>
    <input id="blueRadio" type="radio" ng-model="colorValue" value="blue" /><br />
    <br />
    <strong>Selected color:</strong> {{colorValue}}<br />

  </div>
<script>
angular.module("app", [])
  .controller("radioController", function ($scope)
  {

   });
</script>
</body>

Answer №1

To enhance the functionality of your radio buttons, consider implementing the ng-change function and passing the ng-model value as a parameter.

Example

<div ng-controller="radioController">
      <input type="radio" ng-model="color.name" value="red" ng-change="changedValue(color.name)">  Red <br/>
      <input type="radio" ng-model="color.name" value="green" ng-change="changedValue(color.name)"> Green <br/>
      <input type="radio" ng-model="color.name" value="blue" ng-change="changedValue(color.name)"> Blue <br/>
</div>

View Demo on Plunker

To simplify the HTML structure, utilize the ng-repeat directive to dynamically render elements based on an array of colors.

Example

<div ng-repeat="color in colors">
  <input name="radio" type="radio" ng-model="color.name" value="red" ng-change="changedValue(color.name)"> {{color.name}}
  <br/>
</div>

JavaScript Code

$scope.colors = [{
  name: 'Green',
  value: 'green'
}, {
  name: 'Red',
  value: 'red'
}, {
  name: 'Blue',
  value: 'blue'
}];

Updated Plunker

Answer №2

<script>
angular.module("myApp", [
]).controller("colorController", function ($scope, $log) {
   $scope.$watch('selectedColor', function(selectedColor){
       $log.info(selectedColor);
   });
});
</script>

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

Explore all sorts of data such as search term within a JavaScript JSON array

In my JSON array of objects, I have data displayed in an HTML table. Above the table, there is a search input where users can enter search terms. [ { "id": 1, "title": "My fridge door closed", "description": "The fridge door was closed yesterday.", "point ...

Instructions on integrating a column of buttons into a Bootstrap table containing information retrieved from a MySQL database

My bootstrap table is currently displaying data that is loaded from a MySQL database. I am looking to enhance it by adding a column with buttons, similar to the layout shown in this image. https://i.stack.imgur.com/8fWfR.png However, I am facing some dif ...

extract the ng-model data and send it to an angular directive

In my current project, I have a specific situation where there are multiple text-boxes and when any of them is clicked, the corresponding ng-model should be displayed in the browser console. To achieve this functionality, I came up with the following Angul ...

The Jquery Object #<Object> does not have the 'getElement' method available

I've been attempting to set up this table, following the instructions here: Despite verifying that my browser is correctly pulling the CSS and .js files, I keep encountering an error related to my sortabletable.js file. (screenshot of the error) htt ...

Steps for establishing a connection to a MongoDB database on Heroku using mongoose

Everything is running smoothly with my app locally and it can successfully connect to the local database. However, when I attempt to run it on Heroku, I encounter the following error: 2014-04-17T06:32:23.404458+00:00 app[web.1]: > <a href="/cdn-cgi ...

Stopping a jQuery function from executing multiple times while it is already active - is it possible?

Currently, I am utilizing the http://jsfiddle.net/CqAU2/ plugin for image rotation on my website. The issue I am facing is that when the user clicks on the image box multiple times, it continues rotating each time. I want the click action to only be regi ...

Navigating shadow dom elements in HTML with Selenium WebDriver

public WebElement retrieveShadowRootElement(WebElement element) { WebElement shadowRoot = (WebElement) ((JavascriptExecutor)driver) .executeScript("return arguments[0].shadowRoot", element); return shadowRoot; } WebElement rootElement= dri ...

The upload directory fails to include the folder name when sending a file

After experimenting with the new directory upload feature, I encountered an issue where the server request did not preserve the exact folder structure as expected. Here is the HTML code snippet: <form action="http://localhost:3000/" method="post" enct ...

Is there a substitute for AngularJS $watch in Aurelia?

I'm in the process of transitioning my existing Angular.js project to Aurelia.js. Here is an example of what I am trying to accomplish: report.js export class Report { list = []; //TODO listChanged(newList, oldList){ ...

Implementing $http in AngularJS

I am encountering the following issue: angular.module('myApp').factory('dashboard', ['$http', function ($http) { return { name: function(str){ return str + ':' + 'works!'; ...

Function in Typescript used for checking types and catching compilation errors from external sources

Fact: I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable and returns 'undefined' !== typeof variable). It's quite simple. export function IsDefined(variab ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

Upon clicking, the input texts revert to their original default values

I have a form below that is working as intended, except for one issue. When I click the 'Add' link, the texts in all the textboxes revert to their default values, as shown in the images. How can I resolve this problem? Thank you. before click: ...

Adding DOM elements dynamically from a controller in Angular.js is a powerful feature that

Hey there, I'm just getting started with Angular and may not be using the best practices yet. One thing I'm working on is appending a <circle> element within the controller function called placeShot(), which is triggered by ng-click='p ...

Which delivers better performance: HTTP request from server or client?

Considering the optimal performance, is there a difference in using Angular's HTTP request within a MEAN-stack environment compared to utilizing Request.js or similar for server requests? ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Exploring the issue of why the scroll event handler is not functioning properly within the useEffect hook

After creating a custom hook to retrieve the scroll state of an element, I noticed that the scrollHandler only triggers once. Here's my code: import { MutableRefObject, useEffect, useState } from "react" export const useScrollState = <TE ...

Is there a way to avoid adding this final "faulty state" to the array?

While working on dynamically slicing an array, I noticed that my while loop was causing an extra slice to be added when it broke the conditional. Even though I can achieve the desired functionality by removing the last element with arr.pop(), I am curious ...

What is the best way to link a socket.id with an element in an array?

I am currently working on creating a chat-room where the names of connected users are shown in an 'Online Users' section. The following code snippet adds each user's name to an array and displays the contents of that array. However, if a u ...

eliminate the gap in the MUI Accordion when it is expanded

How can I prevent the Accordion MUI component from moving and applying top and bottom margins to summary elements in expanded mode? I added the following code to the summary element but it doesn't seem to be working. Any suggestions on how to fix this ...