What is the best way to verify the relationship between parent and children nodes in a tree structure?

Check out my Plnkr with nested loops of checkboxes: here

Below is the HTML code for the nested loops of checkboxes:

<ul>
  <li ng-repeat="continent in destinations">
    <input type="checkbox" ng-model="continent.selected">
    {{continent.name}} ({{continent.countries_selected}} / {{continent.countries.length}}) - {{continent.all_selected}}
    <ul>
      <li ng-repeat="country in continent.countries">
        <input type="checkbox" ng-model="country.selected" ng-checked="continent.selected">
        {{country.name}}
      </li>
    </ul>
  </li>
</ul>

The provided JavaScript code watches for checked children checkboxes to update the parent checkbox accordingly.

However, there seems to be an issue where checking the parent checkbox does not affect its children checkboxes.

The desired functionality is to have all children checkboxes checked when the parent is checked, and vice versa.

$scope.$watch('destinations', function(destinations){

  var total_selected = 0;

  angular.forEach(destinations, function(continent){

    continent.countries_selected = 0;

    angular.forEach(continent.countries, function(country){

      total_selected += country.selected ? 1 : 0

      continent.countries_selected += country.selected ? 1 : 0

      if (continent.countries_selected == continent.countries.length) {
        continent.selected = true;
      } else {
        continent.selected = false;
      }

    });

  });

  $scope.select_all = function(continent){
    continent.selected = true;
  }

  $scope.total_selected = total_selected;

}, true);

Answer №1

experiment with this idea - trigger a function when the continent value changes

<input type="checkbox" ng-model="continent.selected" ng-change="parentChange($index)">

in the controller, include another function

$scope.parentChange = function(index) {
    angular.forEach( $scope.destinations[index].countries, function(country) {
      country.selected = $scope.destinations[index].selected;
    });
  };

you may not need to use ng-checked="continent.selected" for the country checkbox.

try using

<input type="checkbox" ng-model="country.selected">

instead of

<input type="checkbox" ng-model="country.selected" ng-checked="continent.selected">

See DEMO on Plunker

Answer №2

When using the ng-checked attribute in a checkbox, you can provide an expression with and/or conditions to determine if it should be checked. This way, the checkbox will be automatically checked based on the specified expression.

<input type="checkbox" ng-checked="child_1 && child_2 && child_3 && child_4 && child_5" ng-model="parent"/> Select All<br/>

No need to create a separate function for computing when each child checkbox is clicked.

Check out this example.

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

RetrieveImageData magically produces a series of unexpected zeros

I'm currently developing a Chrome extension that has the capability to extract RGB values of images on web pages and store them into separate arrays. However, I'm encountering an issue where there are unexpected zeros appearing in the middle of e ...

What is the best way to incorporate tailored validation into reactive forms in Angular?

I'm facing an issue with my form where I'm trying to display a specific error message based on certain conditions. Currently, my form is functioning but it's throwing a type error stating "undefined is not an object". I'm struggling to ...

Having issues with my custom AngularJS directive functionality

app.directive("myData", function() { return { templateUrl: '/my-data.html' }; }); my-data.html file code <tr ng-repeat="employee in employees"> <td>{{employee.id}}</td> <td>{{employee.name}}</t ...

How can we determine if a Node.js application will remain operational?

How is the longevity of a Node.js app determined? For example, consider this code snippet: console.log('Hello World'); In this case, the phrase will be printed and the app will exit immediately. However, with a web server that is actively lis ...

sharing AMD modules between multiple files

As of now, I am in the process of constructing the Ember.SimpleAuth library - a tool designed for facilitating authentication and authorization within Ember.js applications (https://github.com/simplabs/ember-simple-auth/tree/sub-packages). This library pro ...

What is the correct way to navigate data through my Node.js API?

I am struggling with getting the JSON response to display at the /api/orders_count endpoint. Here is a breakdown of my setup: In my project, I have various files: Routes file - where the orders_count route is defined: routes/index.js const express = req ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

I have been tirelessly attempting to resolve this issue, yet all my efforts have proven futile thus

Encountering an issue with web packs and nextjs. import NextDocument, { Html, Head, Main, NextScript } from 'next/document' import theme from '../libs/theme.js' export default class Document extends NextDocument { render() { retu ...

What is the reason behind the controller being unable to locate an Angular model when it contains dots in its name?

I am completely new to Angular and struggling to comprehend this code snippet. app.controller('FileConfigController-detail', function($scope, $http, $stateParams, FileConfigDetailsService) { $scope.detail.inptITResourceID = "test me" ...

Utilizing regular expressions for querying MongoDB

Attempting to retrieve data from MongoDB by querying for a specific field name using regular expressions. For example, if the constant name is set as 'st', the expected result would be 'steven', 'stephanie', and 'stella&a ...

Is it possible to hide a menu by removing a class when the user clicks outside the menu?

I've come across a lot of information about how to close a menu when clicking outside of it, but my question is, can the following code be simplified to something like if you don't click on #menu > ul > li > a then removeClass open. Can ...

What is the best way to retrieve the identity or specifics of the item that was right-clicked within the context menu

My AngularJS populated table includes a link button. When I right-click on this button, I've created a specific context menu using jQuery that pops up. The issue arises when I try to retrieve the ID of the item I clicked on in the context menu (such a ...

Shift the element within the div towards the left side

I am trying to create an animation for an element that moves to the left when hovered over, but the code I thought was correct doesn't seem to be working in my fiddle. Here is the link to the fiddle I created: https://jsfiddle.net/feb8rdwp/3/ Based ...

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

Building web navigation using a combination of HTML, JavaScript, and PHP within a category, sub

I've been struggling to find a detailed tutorial on implementing a dynamic website navigation system using javascript or php. It seems like every time I attempt to research this topic, I end up feeling confused and unsure of where to start. My goal i ...

Using an alias to call a function defined in a separate module in TypeScript

The following code snippet is from the v4.js file located inside the uuid folder within Angular's node_modules: var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { ...

Icons on Google Calendar events - Mini images beside your schedule

I'm in the process of developing a website where I plan to integrate Google Calendar. I want to include a small icon next to specific events to denote certain details. While the "categories" feature in Google Calendar allows me to assign highlight col ...