Issues with Angular radio buttons are causing them to not be selected properly

When it comes to radio buttons, they should be checked based on certain conditions.

<input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes
<input data-ng-checked="!user.contract1 && !user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="false"> No

The model user.agreed holds true or false depending on whether the user has agreed:

  • If the user has agreed to any contract, then user.agreed = true

  • If the user has not agreed to any contract, then user.agreed = false

Sometimes, upon loading the page, the radio button is selected on 'No' instead of 'Yes'. This issue may arise due to the digest cycle completing before fetching data from the server.

I expected two-way binding to ensure that changes in the user model reflect in the view. When data loads from the server, the model updates with new information, and the view should display these changes accordingly.

However, this mechanism isn't working as anticipated. How can I make sure that ng-checked accurately reflects my model's changes?

EDIT controller snippet:

app.controller('TestCtrl', ["QueryService", function(QueryService) {

    $scope.user = {
        contract1 = false;
        contactt2 = false;
    };


    QueryService.getUser().success(function(user) {
        $scope.user = user;
    });

});

Answer №1

Your problem may arise from the simultaneous use of ng-checked and ng-model. It is not possible to utilize both at the same time. While ng-checked only sets the checked property on the element without affecting the value of ng-model, it is advisable to set the value of ng-model instead. Additionally, ensure that radio buttons sharing the same name attribute are grouped together.

A simpler approach would be:

<input name="agree" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes
<input name="agree" data-ng-model="user.agreed" type="radio" data-ng-value="false"> No

and initialize the value with:

 user.agreed = user.contract1 || user.contract2; //Or any other initial value

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

The controller method appears to be unable to detect any parameters

I have been trying to pass an ID in the URL but my controller is not receiving that value. $("#ChangeSlideForm").on("submit", function(){ $.ajax({ type: "POST", url: base_url + "Visualiser/ChangeSlide/21", su ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Utilizing various Material UI Sliders on a single page with shared color properties

After creating a component called "SliderBox", I noticed that it returns a div containing a Material UI Slider with createMuiTheme and an input component. The "SliderBox" component utilizes an onHover method on the parent div to change the component' ...

Using protractor and AngularJS to extract text content from two labels by identifying the elements

My app is organized like this: <ul ng-repeat="variable in link.variables" ng-show="SearchboxCtrl.showData" class="ng-scope"> <li class="ng-binding"> Member Since: </li> <span class="ng-binding"> 2010-01-01 </span></ul& ...

What is the best way to upload a file to a server while working with Vue.js in the Filemanager plugin, or how can I access a global function

How can I upload a file to the server using Vue.js in the Filemanager plugin? I have tried multiple methods and the console log shows that the upload was successful, but I am not able to see any files on the server. Does anyone know what could be wrong? & ...

What are the steps to set a 404 status code in next.js when utilizing ISR with a fallback of "blocking"?

When a route does not match, what is the best way to redirect to a 404 error page and ensure that the status code is displayed as 404 in the network tab using ISR with fallback: "blocking"? ...

Javascript - Relocating a file to a different folder in a node.js environment

I am looking to duplicate a file and relocate it within the directory structure. Current file location: Test.zip -> Account/Images/ -account.png -icon.png -flag.png . ...

Automatically save form field data every 15 seconds in AngularJS without using the $watch function

Is there a way to automatically save form field values every 15 seconds without using $watch? Additionally, the process should stop once the user navigates to a different form. Since there are multiple fields in the form, using $watch may cause performan ...

What is the process for adding a download link to my canvas once I have updated the image?

Is it possible to create a download link for an image that rotates when clicked, and then allows the user to download the updated image? Any help would be appreciated.////////////////////////////////////////////////////////////////////// <!DOCTYPE ht ...

A step-by-step guide on recursively removing all empty array children [] from a nested JSON structure

When I receive a JSON response, I utilize nested JSON data from my GeoRegionCountries APIController and a custom class TreeView to structure the data for a plugin. The specific plugin I am using is a combo multi-select Treeview, accessible through this lin ...

The sequence of event handler executions in JavaScript

When multiple event handlers are attached to the same event on the same elements, how does the system determine the order in which they are executed? Although I came across this thread that focuses on click events, another discussion at this page points o ...

The hit detection algorithm seems to be malfunctioning, and the reason behind it is unclear. (Using Javascript/Processing

I am a beginner in game programming and programming in general. In the past, I have created a clone of "Flappy Bird" and some other games using the hit detection algorithm from the Mozilla Developer Network here. Currently, I am facing an issue while tryi ...

Convert a date from the format of YYYY-MM-DD HH:MM:SS to MM-DD-YYYY using Javascript

Looking to transform YYYY-MM-DD HH:MM:SS into MM-DD-YYYY For instance: Given a date string in the format: 2013-06-15 03:00:00 The goal is to convert this string to 06-15-2013 using JavaScript. Is there a library available for this task, or should I rely ...

Vue.js error: Unable to locate requested resources

Recently, I've been encountering a curious issue when trying to access a specific component in my application. When I manually type the URL http://localhost:8080/detailed-support/start into the browser, the content loads without error. However, none o ...

Tips for Using AJAX and JavaScript to Save an XML File

My current task involves attempting to insert an element into an XML file. Upon inspecting the program with a debugger, I noticed that the element is successfully added to the XML file. However, when I stop the program from running, the changes are not sav ...

Converting JSON data from ASP.NET MVC to a Canvas.js chart

Despite my efforts to find a solution by looking through similar posts, I am unable to resolve the issue. Within my asp.net MVC controller, I have a method called public object OfferChart() List<Det> obj = new List<Det>(); foreach ...

Looking for guidance on implementing a straightforward nested for loop in a Node.js environment

I am facing an issue with my code that is meant to generate a 10x10 grid. Since transitioning to Node.js, I am struggling to make it work correctly due to my synchronous thinking pattern. Currently, the Y values are being assigned directly to 10 for all X ...

Trigger file download with ajax and php

I have been using an image picker plugin to select an image and then force it to download. Initially, I hard coded the PHP which worked perfectly fine. The download pop-up appeared and I was able to view the file without any issues. However, when trying to ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Issues with MySQL not functioning properly when using Promise.All in a Node.js environment

When it comes to running multiple mysql queries asynchronously in express node.js, MySQL works well with simple callbacks. However, I wanted to take it a step further by using async await with promise.all. I also experimented with promise.allSettled, but u ...