"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

I'm having trouble navigating in react-router 4, the route keeps redirect

Can someone help me figure out why all the links are redirecting to a blank page? The dependencies I'm using are: "react-router": "^4.2.0", "react-router-dom": "^4.1.1", App.js import { BrowserRouter, Route, Switch } from 'react-router-dom&ap ...

What is the process for extracting values from a Proxy object and assigning them to a local variable?

Can anyone help guide me on how to retrieve a list of devices (video and input/output audio) using navigator.mediaDevices.enumerateDevices()? I created a function that returns the result, but when I try to display it with console.log(result), I only see a ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

The functionality of Ajax is limited when it comes to handling multiple div elements at the same

Seemingly silly question ahead, but I've been grappling with it for days to no avail. If anyone can help me solve this, please state your price and provide your PayPal details – the money is yours :). What I'm trying to achieve is to add a "Add ...

Showing Nested Json as separate columns in the user interface grid

Every time I make a rest call, I receive an array of nested objects that vary for each outer object... For example: $scope.data = [ { id :5, nested : [ {name : 'S ...

Several JavaScript functions require a confirmation dialog to be displayed before they can be executed

There are three separate javascript/jquery functions in my code, all triggered by a button click. One function posts to a form handler, another creates a new tab, and the third one sends new data into the tab through an ajax call. These functions are inter ...

Acquire HTML table information in array format using JavaScript

I am searching for a script that can extract the 2D array of rows and columns from an HTML table within a div element. The desired array output should be: [ ["Company", "Contact", "Country"], ["Alfreds Futterkiste", "Maria Anders", "Germany"], ...

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...

How can I incorporate JSON data retrieved from my backend server into the content of Tabs in a ReactJS application, utilizing either the map() or forEach() method

I need help assigning a key from an object to each tab using a loop in order to navigate to its content when clicked on. I attempted to use map() but it didn't work, so I'm looking for guidance as I am new to React. Below is the code. Any assist ...

Encountering issues when trying to incorporate SASS and CSS libraries in NextJS

I have been attempting to integrate the wix-style-react plugin into my NextJS project, but I am encountering difficulties when trying to build. According to their documentation, they utilize Stylable, SASS, and CSS Modules. After installing the plugin and ...

The print preview is unable to display all of the barcode images

Currently, I am utilizing the Jqprint plugin for printing purposes. Here is the code snippet for printing a barcode: HTML Code: <div class="wrapper_template" id="print_template"> <div class="imageOutput" > // Insert Barcode Printing Code ...

Is there only a single particle in Three.js?

I am trying to add a single particle to my scene and have the ability to move it around. However, my attempts to do so without using a Particle System have been unsuccessful. Whenever I try to render the particle as a mesh, nothing appears on the screen. I ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

What is the purpose of using an open quote and bracket in the `eval('('+jsonString+')')` syntax for parsing a JSON string?

What is the rationale behind this particular syntax structure? eval('(' + jsonString+ ')') When it comes to parsing JSON text, Crockford explains that "The text must be wrapped in parentheses to prevent any confusion with JavaScript& ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Surprising Regex Match of ^ and special character

My regular expression is designed to break down calculator input strings, such as 12+3.4x5, into individual tokens like 12, +, 3.4, x, and 5 Here is the regular expression I am using: \d+\.?\d+|[\+-÷x] However, I am encountering une ...