Choose the designated radio button option automatically depending on the value received from the server

In the process of creating a quiz engine using angularjs, I have successfully loaded questions with options and implemented the NEXT and BACK buttons. However, I am facing a challenge with pre-selecting the previously chosen option when the user clicks the BACK or NEXT button after answering a question.

For each question, there are 4 options, and I am using a property called 'IsSelected' on the choices to track the user's previous selection.

I am trying to ensure that when users are reviewing their answers, the previously selected option should be automatically checked by default. This is where I am currently stuck. I have come across a similar question that discusses setting a default value for an Angular JS Radio Button:

Need to Default select an Angular JS Radio Button which provides some guidance on setting default values, although not exactly for this scenario.

HTML Code:

<div class="col-lg-offset-2 col-lg-5" data-ng-repeat="item in items" style=" border:#000 1px solid;padding:10px 40px 40px 40px">
        <h3 style="color: #0000ff">Question <b style="color:red">{{item.QId}}</b> of <b style="color:green">{{item.QCount}}</b></h3>
        <div>


            <!--<div id="first">{{item.QId}}</div>-->
            <h2>{{item.QId}}. {{item.QText}} </h2>
        </div>
        <div data-ng-repeat="choice in item.AnswerCh">

            <input type="radio" name="choize" data-ng-model="choice.IsSelected" value="choice.IsSelected" /> {{choice.Text}}

        </div>
        <br />
        <div id="ref" style="display: none">{{item.QId}}</div>
        <div id="you">{{choice.choize.Text}}</div>

JS Code:

        $scope.getNext = function () {    
            var quet = $('#ref').html();
            var answ = $('#you').html();
            cbtFact.getNext().update({q:answ,v:quet },
            function (data, status, headers, config){         
                $scope.items = [];
                
                $scope.items = data;
            },
            function (data, status, headers, config) {
            });
        };

        $scope.getPrevious = function () {
            var quet = $('#ref').html();
            var answ = $('#you').html();
            cbtFact.getPrevious().update({ q: answ, v: quet },
            function (data, status, headers, config) {
                $scope.items = [];
                $scope.items = data;
             
            function (data, status, headers, config) {
            });

        };
        

Answer №1

Have you considered utilizing ng-if in the following manner?

Check out this Fiddle for reference

<div data-ng-repeat="choice in item.AnswerCh">
   <span ng-if="choice.IsSelected">
      <input type="radio" name="choize" data-ng-model="choice.IsSelected" value="choice.IsSelected" checked/> {{choice.Text}}
   </span>
   <span ng-if="!choice.IsSelected">
      <input type="radio" name="choize" data-ng-model="choice.IsSelected" value="choice.IsSelected" /> {{choice.Text}}
   </span>
</div>

Alternatively, you could also consider using the Angular Js ngChecked attribute

Explore this Fiddle for implementation

 <div data-ng-repeat="choice in item.AnswerCh">    
     <input type="radio" name="choize" data-ng-model="choice.IsSelected" value="choice.IsSelected" data-ng-checked="choice.IsSelected" /> {{choice.Text}}    
 </div>

Update:

By using ng-model and ng-value

View this Fiddle to see it in action

While both of the above approaches are functional, it seems that they may present some challenges when used alongside ng-model.

According to the Angular Js documentation, the desired functionality can be achieved by simply utilizing ng-model and ng-value as shown below, which is considered the recommended approach. ng-value represents the value to be assigned to the expression when selected.

<div data-ng-repeat="choice in item.AnswerCh">
        <input type="radio" name="choize" data-ng-model="choice.IsSelected" ng-value="true" /> {{choice.Text}}       
 </div>

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

Error message in JS/Ajax alert box

I keep receiving an alert box saying "Image uploaded" even when the variable $imagename is empty. Below is the script in question: <script> function ajax_post1(ca){ var cat = ca; var name = document.getElementById("name").value; var ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

What is the best method for preserving HTML content using Ajax?

I am having difficulty storing HTML code in a database using AJAX. Despite having the correct connection information, I am unable to write to the table. <div id="others"> <div id="name"><input type="text" name="results" class="name"> ...

What is the best way to add external javascript files to bookmarklets?

I have been developing a CDN for a collection of scripts that I created for my job. Previously, I had to distribute these scripts individually and each user would have to download and install them on their own computer. Now, I am transitioning them to an A ...

In the process of creating my initial discord bot, struggling to incorporate advanced functionalities beyond basic commands

I am currently using discord.js and JavaScript to code. I have created a test bot and followed step-by-step guides meticulously, but the bot only responds to basic "ping pong" commands. Whenever I try to add more complex commands, the bot stops functioning ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

How about this: "Can you turn a picture into text with just one click?"

Seeking assistance to enhance the 'About Us' page on our website. Each team member has a profile with their email address listed below, but we want to add a picture that disappears when clicked, revealing the email address in its place. You can ...

Creating flexible items with a 1:1 ratio and ensuring that the padding on the left and right of the flex container remains consistent

Whenever I adjust the size of the window, https://i.sstatic.net/Fm3d1.png the flex-container ends up with uneven padding on the left and right, which is less than ideal. So, I am looking for a way to allow the flex-item to resize when the window size c ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

mobile navigation menu remains open after selecting a link

When the Fixed-to-top navbar is used in mobile view, such as clicking a Navbar icon, it does not collapse afterward while the page is loading. How can I prevent the page from loading in the navbar section? Here is the link to my website: CLICK HERE Addi ...

Is there a way to use a single function to fill and calculate multiple input fields with PHP, Javascript, and

I've encountered an issue while trying to populate a form using Javascript/ajax/php. The problem is that my function only fills in one of the required forms and then stops, even though I have received the second response from the server. Here's ...

Creating a dynamic search feature that displays results from an SQL database with a dropdown box

Is there a way to create a search bar similar to those seen on popular websites like YouTube, where the search results overlay the rest of the page without displacing any content? I've searched extensively on Google and YouTube for tutorials on databa ...

Encountered a JavaScriptException while trying to click on an element using Selenium and Python: "arguments[0].click is not a function"

When practicing web scraping, I have been extracting locations from various websites. This particular code helps me pinpoint individual city locations of a hotel brand. However, every time I use driver.execute_script("arguments[0].click();", button) in my ...

State not visible in Redux Devtool extension on Chrome browser

I am still getting acquainted with Redux, especially the Redux DevTools. Recently, I developed a simple application where users can be clicked on to display their information. Essentially, the state contains the currently selected user. However, for som ...

Utilize Node.js and Cheerio to extract data from an HTML table

Having trouble converting an HTML table to JSON. HTML table structure: <div id="content"> <h1>content-information</h1> <table class="testinformation"> <thead> <tr> ...

"Disabling a FormControl within a FormArray in Angular 4: A Step-by-

I've come up with a code snippet below that I thought would disable the FormControl in a FormArray. some.component.html <form [formGroup]="testForm"> <div *ngFor="let num of countArr"> <input type="text" formNameArray="arr ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...

What is the best way to implement a 5-second delay after the timer reaches 00:00?

I am in the process of creating a countdown timer for an application. Once the timer reaches 00:00, I would like to add a 5-second delay before it starts counting down again. How can I achieve this using setTimeout()? function initiateTimer(duration, di ...

What is the best way to trigger a function on every navigation event in a React Native application?

Here is my scenario: We are currently working on adding an inactivity timeout feature to a react native app. The goal is to have the timeout reset every time a user interacts with the app or navigates between screens. At the moment, we have a callback fu ...

Displaying content inside a directive based on a condition

I am working on a directive that includes an ngShow statement based on a specific attribute or condition that needs to be passed. It's interesting how when I hardcode the ng-show, everything functions correctly. However, if I attempt to assign the val ...