"Troubleshooting an issue with ng-model not functioning properly with radio buttons in Angular

I'm a newcomer to Angular and I'm attempting to retrieve the value of the radio button selected by the user using ng-model. However, I'm not seeing any output in "selected contact".

Check out My HTML below:

<!doctype html>
<html ng-app>
  <head>
    <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <form name="myForm" ng-controller="Ctrl">
      <table border="0">
                <th>Contact Type</th>
                <tr ng-repeat="contact in contacttype"><td>
                <input type="radio" ng-model="contactname" name="group1" value="{{contact.name}}">{{contact.name}}                  
                </td>               
            </td></tr></table>
      <tt>selected contact = {{contactname}}</tt><br/>
     </form>
  </body>
</html>

Here's my main.js content:

  function Ctrl($scope) {
  $scope.contacttype = [ 
                          {name: 'Both' }, 
                          {name: 'User'},
                          {name: 'Admin'}
                          ];
}

Could you help me figure out what went wrong here? I'm quite stumped at the moment!

Answer №1

The reason you are facing this issue is because ng-repeat generates its own scope, and you are attempting to assign a value to the parent scope from within the child scope. To solve this, you can try the following:

<input type="radio" ng-model="$parent.contactname" name="group1" value="{{contact.name}}">

Answer №2

While facing a similar issue, I attempted to use $parent with ng-model but found it ineffective. The root of my problem lied in assigning identical name attributes to multiple groups of checkboxes. This caused the default checked radio button to become hidden within the final group.

Ensure that each distinct group has its own unique name attribute for proper functionality.

Answer №3

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {

$scope.devices = [{
nameD: "Device 1"
}, {
nameD: "Device 2"
}, {
nameD: "Device 3"
}, {
nameD: "Device 4"
}];

});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app-controller-r.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form>
<ul>
    <li ng-repeat="device in devices">  
<label>{{device.nameD}}
        <input type="radio" ng-model="$parent.deviceType" value="{{device.nameD}}" />       
</label>
    </li>
</ul>
<button>Submit</button>
</form>
{{deviceType}}
 </div>
</body>
</html>

Answer №4

When using the directive multiple times and utilizing the for and id attributes with labels, be sure to reference the scope's $id.

<li ng-repeat='add_type in types'>
    <input id="addtester_{{ add_type.k }}_{{ $parent.$id }}" type="radio" ng-model="$parent.addType" ng-value='add_type.k' class="tb-form__input--custom" /
    <label for="addtester_{{ add_type.k }}_{{ $parent.$id }}">{{ add_type.v }}</label>
</li>

Failure to do so may result in directives sharing the same inputs and causing them to function incorrectly.

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

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

"Effortlessly transform a JSON string into a JSON Object with JavaScript - here's how

When I serialize my object using the ASP.net JavaScriptSerializer class and return it to the client side, how can I deserialize the string in JavaScript? ...

Error occurs in React Native when trying to import routes due to type mismatch

My react native app is running on my physical device, but I encountered an error when importing routesContainer in my app.js. Can anyone shed some light on why this error is occurring? TypeError: Super expression must either be null or a function [Mon Oct ...

Using JavaScript: Retrieve the URL from a JSON file and run it in the background

I am looking to make a JSON request using jQuery: $.getJSON('http://example.com/file.php', function(data) { //data }); An example of the JSON output: { "url":"http://example.com/execute.php" } Next, I want to silently execute the URL on th ...

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

Is there a way to obtain asynchronous stack traces using Node.js and TypeScript?

When working with TypeScript, I encountered an issue with stack traces. It seems that only the bottommost function name is displayed. My setup includes Node.js v12.4.0 on Windows 10 (1803). Below is the code snippet: async function thrower() { throw new ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Once a session is established within a route, it cannot be accessed or utilized in any other routes within the

I am currently in the process of setting up sessions for my node.js app. To achieve this, I am utilizing modules such as "express", "express-session", and "express-mysql-session" to store the sessions in a database on my server. While my code works perfect ...

Get the hash value after a specific character using Javascript

I'm currently working on a website with ajax functionality where pages load when clicking on navigation buttons. However, I encounter issues when reloading the page as it defaults back to loading main.html, regardless of the URL. The hash being used i ...

Retaining the data retrieved from a successful $.ajax call's done() function

After successfully retrieving the desired information in the done method, I encountered an issue when trying to assign it to a variable with broader scope. This approach had worked fine with $.each(...), leading me to assume that it would work here too. v ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

What are the steps to generating and sharing 'npm create' scripts?

I am looking to develop and release a script on npm that functions similarly to: npm create qwik@latest or yarn create next-app --typescript However, I am unsure where to begin. Despite searching extensively online, I have not been able to find any helpf ...

Customized selection groups for dropdown menu based on alphabetical order

I am dynamically generating a select list from an array of data and I want to group the options alphabetically. For example, here is the data: data = [ ['bcde','21254'], ['abcd','1234'], ['abcde',' ...

The problem I am facing is with the React Ant d Modal Component, where I am unable to render the

Hey there! I'm currently working with React Js and the 'Ant design Modal Component'. When I click on a button, the modal should open and display the content of each user with their unique ID. However, I'm facing an issue where all modal ...

The parsing of source maps fails due to issues with the .htaccess file

After analyzing the web page, I found that the .htaccess file contains the following code: RewriteEngine On RewriteBase / Options -MultiViews DirectorySlash Off # skip POST requests RewriteCond %{REQUEST_METHOD} POST RewriteRule ^ - [L] RewriteCond %{R ...

The issue with alignment in Angular Material components remains unsolved

When the screen size is larger than small, layout-align works well. However, when it is smaller than small, layout align does not work. <div layout-gt-sm="row" layout-lt-sm="column" flex layout-align="space-around center"> <!-- main content ...