When using ng-checked in Angular, the DOM may not display the element.input.checked property even when the

I am having issues with using ng-checked to automatically check a checkbox when a modal loads under certain conditions. Despite the item being checked, the condition if (item.checked) returns false.

Below is the directive I am working with.

app.directive('toggleButtons', [function() {
    return {
        link: function(scope, element) {
            var toggleButtons = element.find('.input-add-checkbox');

            function checkState() {
                Array.prototype.forEach.call(toggleButtons, function(each) {
                    if (each.checked)
                        each.parentNode.style.backgroundColor = "#00E0AA";
                    else if (!each.checked)
                        each.parentNode.style.backgroundColor = "transparent";
                });
            }

            Array.prototype.forEach.call(toggleButtons, function(each) {
                each.addEventListener('click', function() {
                    checkState();
                });
            });

            checkState();
        }
    }
}])

My HTML code looks like this:

<label for="listen" type="button" class="type-toggle btn btn-green">
    <input type="radio" id="listen" name="type" value="listen" ng-checked="{{ currentState == 'app.listen' }}" ng-model="contentParams.type" class="input-add-checkbox" />
    <span class="glyphicon glyphicon-headphones"></span>
</label>

Despite the item being checked, the style defined in the JavaScript is not properly applied when the template containing the directive is loaded, possibly due to it being within an AngularUI modal. Even using a timeout has not resolved the issue.

Here is where and how I implement the directive.

Answer №1

Instead of resorting to complex logic, simplify by using only ng-model and value:

<input type="radio" id="listen" name="type" 
  value="app.init" 
  ng-model="contentParams.type" class="input-add-checkbox" />

This way, the radio button will be selected when the ng-model matches its value. Rather than checking if(each.checked), compare values with

if(scope.contentParams && each.value === scope.contentParams.type)

Another approach is to use ng-attr, which has limitations, but can work initially. In the checkState function, you'll still need to compare value with scope.contentParams.type

 ng-attr-checked="{{contentParams.type === 'app.listen'}}

Check out this working example

Answer №2

Avoid combining ng-checked and ng-model in AngularJS. It is recommended to choose between using ng-checked with ng-click or ng-model with ng-change.

Related query: AngularJS: ng-model not binding to ng-checked for checkboxes

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

Assess html code for Strings that include <% %> tags along with embedded scripts

Having a small issue with my code where I am receiving an HTML response from a web service as a java String. I need to display this String as HTML on my webpage, but the problem is that there are some script tags in the form of <% ... %> which are sh ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

Various colored backgrounds in a random arrangement on a grid post layout

I'm looking to implement this plugin for displaying blog posts, but instead of using an image as the background, my client wants different colored images. I have managed to figure out the code to achieve this based on a post I found here, but unfortun ...

Can I assign a custom form id before manually triggering submission using AJAX?

I have developed an interesting code snippet that uses AJAX to submit a form only if the form has an ID attached to it. $(document).delegate('form', 'submit', function(event) { var $form = $(this); var id = $form.attr('id& ...

Utilize ng-options to iterate through a dictionary object

I have an object called "a" that I need to loop through using ng-options: var a = { 'optionName1': 'optionValue1', 'optionName2': 'optionValue2', 'optionName3': 'optionValue3', 'optionName4& ...

Error Message: A key is being provided to the classes property that is not implemented in the current context

Trying to customize Material-UI styles with makeStyles() as outlined in the documentation but encountering a warning when passing a classname in the parent component that is not specified in useStyles. The warning message reads: Warning: Material-UI: th ...

Run the function once the page has completed downloading and bootstrapping

After experimenting with $evalAsync and $viewContentLoaded, I've found that they only trigger after Angular has completed populating the template. My goal is to determine, from within a directive: Is the template fully replaced by Angular? Have all ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

ExpressJS - The execution of JavaScript in this framework does not strictly follow a top-down approach

Having issues with this particular script not running as expected, particularly in the variable reassignment section. Below is the code snippet and output: // Code to Create New Open Market in the game let latestRowId = 1; var sqlQu ...

Is there a way to select an element within a nested list item only when the preceding list item is clicked using Jquery/JavaScript?

I am working with an unordered list that looks like this: <ul> <li><a class="foo" id="one">some text</a></li> <li><a class="foo" id="two">some text</a></li> <li><a class="foo" id="thr ...

An issue arises when using JSON.parse() with regular expression values

I am encountering an issue with parsing a JSON string encoded with PHP 5.2 json_encode(). Here is the JSON string: {"foo":"\\."} Although this JSON string is valid according to jsonlint.com, when using the native JSON.parse() method in Chrome a ...

Create Vuetify components dynamically through programming

My goal is to dynamically create Vuetify components and insert them into the DOM. I've had success with simple components like v-card or v-dialogue, but I'm running into issues with v-data-tables. To demonstrate the problem, I set up a codesandb ...

Determine if a Node.js Express promise holds any data

I'm looking for assistance with my nodejs application that returns a promise. What I need help with is figuring out how to determine if the result of this promise contains data or if it's just an empty array. I attempted using Object.keys(result) ...

Executing a conditional onClick function when the page loads

I have implemented a php-based authorization system that loads different authorization levels into a JavaScript variable. My goal is to disable certain onclick events based on the user's authorization level. I've come up with the following code ...

Sliding content with the grace of a visual journey

I'm currently working on a content slider that is very similar to this one. My goal is to make it rotate automatically, but I've been struggling to get it to work. I've attempted various methods, including triggering a click event on the lin ...

Is the concept of Controlled and Uncontrolled Components in VueJs similar to that of React?

When it comes to React, there is a distinction between controlled and uncontrolled components explained in detail at this link. Controlled components function within the React model where state is managed in the virtual DOM. In contrast, uncontrolled com ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...

Do not allow navigation to another page until the form has been submitted

As part of my project, I have implemented a feature where new users are required to change their password upon logging into their account for the first time. For new users, the Change Password screen is displayed immediately after login. The menu options ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...