Using ng-checked directive with a radio button in AngularJS

Within my angular application, I have implemented a loop to iterate through a collection and display the records using input type="radio".

<tr ng-repeat="account in vm.pagedAccounts.items"
                ng-class="{ 'highlight': (account.rowIsSelected) }"
                <td>
                    <input
                        ng-model="account.rowIsSelected"
                        value="{{account}}"
                        name="selectedAccount"
                        ng-checked="account.rowIsSelected"
                        ng-change="vm.selectAccount(account)"
                        type="radio">
                </td>

Initially, in the controller, I ensure that the rowIsSelected property is set to false for all accounts.

response.data.results.forEach(function(account) {
   account.rowIsSelected = false;
});

The functionality is working as expected, with the ability to highlight the selected account.

However, in the selectAccount function, I want to handle the scenario where clicking on a different account will clear previous highlights and only highlight the currently selected one.

    vm.selectAccount = function (account) {
        if (account.rowIsSelected) {

            // Reset all accounts to false
            vm.pagedAccounts.items.forEach(function(account) {
                account.rowIsSelected = false;
            });

            var selectedAccount = vm.pagedAccounts.items
                .filter(function(x){
                    return x.id=== account.id;
                });

            // Set the property of the selected account to true
            selectedAccount[0].rowIsSelected = true;
        } 

However, when clicking on the same row twice, it is no longer highlighted. I want to maintain the highlight for the selected account.

Could someone guide me on how to achieve this? Is my current approach correct? Any assistance would be appreciated.

Answer №1

Give this a shot.

vm.chooseOption = function (selectedItem) {
    var chosenOption;
    vm.options.list.forEach(function(option) {
        if(selectedItem.id == option.id){
            chosenOption = option;
            option.isSelected = true;
        }else{
            option.isSelected = false;
        }
    });
    //Now only mark that option as selected
    chosenOption[0].isSelected = true;

}

Answer №2

You might want to consider rearranging the layout of your radio buttons, following the suggestion provided by angularjs

Perhaps something along the lines of:

<tr ng-repeat="account in vm.pagedAccounts.items"
    ng-class="{ 'highlight': vm.pagedAccounts.selected === account }">
    <td>
        <input
            ng-model="vm.pagedAccounts.selected"
            ng-value="account"
            type="radio">
     </td>
...

Make sure that the radio buttons are automatically selected when the ng-model value matches the ng-value, eliminating the need for specific logic or ng-checked, etc.

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

Converting a ReadStream to a ReadableStream in NodeJS: A Step-by-Step Guide

This question poses the opposite scenario to converting a ReadableStream into a ReadStream. ReadStream is a data structure utilized in Node.js ReadableStream is a structure that comes from the web platform, as detailed here As new runtimes like Deno or t ...

What are the steps for defining a package once and utilizing it across multiple pages?

Hello, I'm new to Next.js and I have a question regarding the code organization. In my project, I have two pages: PostList (index.js) and PostSingle ([postId].js). I want to implement a feature that allows users to switch between dark and light theme ...

The ng-app feature is causing the script to run endlessly

Currently, I am troubleshooting an issue within my angular application that is built on the asp.net web application empty template. The problem arises when I utilize ng-app; if I leave it blank, the $routeProvider fails to initialize. However, if I specify ...

What is the best way to utilize the useSWR hook when there are necessary logical operations to be performed on the response before proceeding with the next API call

I am currently utilizing the swr library in a Create React App and require the usage of the useSWR hook for data fetching that is both contingent and conditional. The specific task at hand involves: Making an API call to retrieve an id which will be used ...

Utilizing MEAN.js for uploading images

Following a tutorial on the MEAN stack, I am looking to implement an image upload feature using MongoDB on a server. Resources: Angular directive for file uploads create-spot.client.view.html <div data-ng-controller="SpotsCreateController"> &l ...

Fixing the error: "React-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a valid function"

Every time I change the option in the selector, I keep encountering this error: "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function" :( import React from "react"; import Product from "./Product" ...

How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time. Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be v ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Webpack failing to load jQuery correctly

In the process of transitioning my application.js application into smaller page bundles using SplitChunks, I have encountered a situation in my users/show.html.erb page where I am utilizing the following tag to import the specific chunk. <%= javascript ...

Disable automatic playback of HTML video

There is an HTML video with an image that loads initially and then disappears to play the video. I would like the image to always be visible until I click on it. Once clicked, the video should start playing. You can view the code on JSFiddle: http://jsf ...

Tips for integrating a "datetime" picker in your AngularJS application

Currently working on an AngularJS application. The single page has a date input that needs to be added. Date Input <input type="date" ng-model="InputDate" /> Any suggestions on how to accomplish this task? ...

How can I insert an empty option following a selected value in a dropdown menu using jQuery?

How to use jQuery to insert a blank option after an existing option? I attempted to add a blank option, but it ended up at the top of the dropdown. I actually need one existing option followed by one blank option. For example: <option></option& ...

Exploring the capabilities of Google Drive API using Requests library

I am interested in streaming a file from a remote source to Google Drive. By utilizing the request library, you can easily download files locally like so: request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png') ...

Divide and conquer- Lighttpd's mod_wstunnel combines separate messages by using UNIX socket communication to the backend server

In my experience with lighttpd's mod_wstunnel, I have encountered a peculiar issue. When I send two messages in quick succession from the backend using a UNIX socket to communicate between lighttpd and the backend, I noticed that lighttpd logs show th ...

The issue I am encountering is that the keyboard controls in JavaScript are not causing the

One of the key elements in my code revolves around JavaScript functionality. I have implemented a feature where objects can be moved by pressing keys such as "down" or "right". However, there seems to be an issue where an object loaded from a .json file is ...

Issue with displaying custom in-line buttons in JQGrid

Currently, I am utilizing jqgrid 3.8.2 (I am aware it's not the latest version, but I plan on updating it soon after seeking some advice :-)) I have successfully incorporated a couple of in-line buttons into my jqgrid using the default formatter &apo ...

Adjust the size of an image and move its position both vertically and horizontally using Javascript

I am currently working on transforming an image both vertically and horizontally, as well as scaling it using JavaScript. While I have managed to resize the image successfully, it doesn't quite look how I want it to. I am aiming for a similar effect a ...

Utilizing a Bootstrap 3 modal within an AngularJS application with html5mode

How to display Bootstrap Modal in the first click when using html5Mode(true). When clicking on launch demo modal, the URL changes to /#myModal upon the 1st click but the modal does not appear. The modal only appears upon clicking launch demo modal again. ...

Obtaining the response object for the web browser

Greetings! I currently have a function within router.js in NODEJS : const authenticateUser = (req, res, next) => { //something }; Whenever my application is live, this function is triggered. I am looking for a way to examine the response object. Is ...

What is the method to store and retrieve data attributes linked to elements such as select options within the React framework?

Despite my efforts, I'm currently unable to retrieve the data attribute from an option using React as it keeps returning null. <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}> <opti ...