How can I use Angular to add ng-class to a parent element when a checkbox is selected?

I am working on a parent list with a dropdown of checkboxes that only shows when you click on the list. Currently, all lists receive the class "active" if any checkbox in any list is checked. However, I want to change this behavior so that only the list containing the checked checkboxes gets the "active" class. How can I modify the code to achieve this?

HTML:

<ul ng-repeat="type in filterTypes">
    <li ng-repeat="filter in type.filters" ng-class="{active:checked}">{{filter.value | uppercase}}
        <ul>
            <li ng-repeat="option in filter.options">
                <label>
                    //if any checkbox is checked, the active class should be given to the parentd list at the way top.
                    <input type="checkbox" ng-model="checked"/>
                    {{option}}
                </label>
            </li>
        </ul>
    </li>
</ul>

Directive:

return {
    restrict: "E",
    templateUrl: 'scripts/directives/all-filters.html',
    link: function(scope, el, attr) {
        scope.filterTypes = dummyData.filters;
    }
}

Answer №1

To ensure each option has the checked property applied, update the model to ng-model="option.checked"

Next, modify the li element's ng-class directive to execute a function that checks if any options within the filter are marked as checked

$scope.areAnyOptionsChecked = function(filter) {
    for (var i = 0; i < filter.options.length; i++) {
        if (filter.options[i].checked) {
            return true;
        }
    }
    return false;
}

If the function returns true, add the active class to the element

ng-class="areAnyOptionsChecked(filter) ? 'active' : ''"

Answer №2

<label for='toggle' ng-model='checked' ng-click='filter.checked=checked'/>

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 animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

After refreshing the page, the ngRoute white page is displayed

I've encountered an issue with my Angular website. I built it using ngRoute, but when I click on a link, a white page appears. Only after refreshing the page does the content actually show up. Even in the browser's DevTools, you can see the html ...

React - How to Close Material-UI Drawer from a Nested Menu

Currently, I am utilizing a fantastic example (here) to create a dynamic nested menu for my application. Taking it a step further, I am trying to integrate it into a Material UI appbar/temporary drawer. My goal is to close the drawer when the user clicks o ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

The AJAX server call is still experiencing a timeout issue despite having already implemented a timeout

My server ajax call keeps timing out even though the server responds back within a reasonable timeframe. If the server responds within 2-4 minutes, the ajax call goes into success. However, if the server takes longer than 4 minutes to respond, the ajax ca ...

Is there a way to utilize the child component's method?

I am looking to access a child component's method from the parent in Vue.js. To achieve this, I plan on using $refs. Code Example: <template> <div>Parent!</div> </template> Script: <script> Vue.component('c ...

Creating multiple synchronous loops within a Vue component using JavaScript

I'm dealing with a JavaScript loop that processes data from an Excel file. The loop loops through the results and retrieves a list of PMIDs. If the PMIDList has more than 200 items, it needs to be split into segments of 200 for processing due to restr ...

Facebook's Thumbs Down to My Code

I've been struggling to integrate a Facebook Like button on my blog using the following code: $("#fblike").append(" <iframe src='http://www.facebook.com/plugins/like.php?app_id=217624258276389&amp;" + window.location.href + "&amp;send ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...

Commitment failing to deliver the information

I am currently attempting to retrieve data based on a specific ObjectId using promises. The function is successfully fetching the data from the database, but it is failing to return the result as expected. Below is the code snippet: getScreenDetails = fun ...

What are the differences between jQuery, jQuery Mobile, and jQuery UI?

As someone fresh to web development, I find myself overwhelmed by the numerous frameworks available. I am interested in learning about the distinctions between these frameworks and how they can benefit my projects. Additionally, I am curious as to why jQu ...

What is a global variable used for in JavaScript?

Here is the code snippet that I am currently working on: $(".link").each(function() { group += 1; text += 1; var links = []; links[group] = []; links[group][text] = $(this).val(); } ...

ng-class does not seem to be functioning properly when used within a file that is included via ng-include in

My question pertains to the menu I am loading using ng-include from the index file. <span ng-include="'app/components/common/menu.html'"></span> The content of menu.html is as follows: <li ng-class="active" > <a hr ...

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

Can I use my local network/browser to download an html file from a webpage as if I manually downloaded it using javascript or nodejs?

As someone who is relatively new to javascript/nodejs and its packages, I have a question about downloading files. Is it feasible for me to download a file using my own local browser or network? Typically, when researching how to scrape or download html ...

Troubleshooting 404 errors with Cordova, AngularJS, and Node.js (Express) when using $http with

I'm currently testing in an Android environment using Cordova, AngularJS, and Node.js (Express). I'm attempting to retrieve some data using $http(), but consistently encountering a 404 error message (as seen in the alert below). Here's the ...

Exploring the method of inserting an element into a nested array using JavaScript's ES6 features

Let's say I understand how to use the spread operator to add an element to a regular array in ES6. const arr = ["a","b"] const newArr = [...arr, "c"] This would result in ["a","b","c"] But when it comes to implementing this with a nested array, like ...

A guide on updating table rows in Material UI and React Table

I am currently developing a table using Material UI/React that consists of multiple text fields per row and permits users to delete specific rows. Each row in the table is generated from a list, and I am utilizing React's state hooks to manage the sta ...

ng-grid Adjusts its Height Automatically

Is there a way to make ng-grid automatically resize its height based on the page size? The official documentation for ng-grid suggests using a fixed height, but I found a helpful solution in this link: .ngViewport.ng-scope { height: auto !important; ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? https://i.sstatic.net/mEEMS.jpg HTML <label><span class="r ...