Accessing Parent and Child Values in AngularJS Selections

I am seeking advice from experts on how to achieve the following desired results:

Expected workflow chart:

https://i.sstatic.net/9ZmmT.png

Here is the default view:

https://i.sstatic.net/H6xkZ.png

Scenario 1: By clicking on the number "1", all items from left to right and their children should be highlighted as shown below:

https://i.sstatic.net/3L8h2.png

Scenario 2: Following Scenario 1, if we click on the number "3", the highlight for all items from left to right and their children should be removed since 3 is considered the parent/root:

https://i.sstatic.net/qQoQP.png

Scenario 3: Back to the default view where there is no selection, selecting the number "18" should highlight all parent values like so:

https://i.sstatic.net/4H3hs.png

Scenario 4: After performing Scenario 3, clicking on the number "18" specifically should remove the highlight just for 18. There is no need to deselect parent levels when moving from right to left:

https://i.sstatic.net/3y4OT.png

Note: Deselecting parent levels from right to left is not required for any value.

For reference, here is the code: JSFiddle

  $scope.setActivePrevNext = function (arr) {
        let c;
        arr.RowValues.forEach(e => {
            e.isActive = !e.isActive; c = e.isActive;
        });
        index = $scope.groupOfCheckboxes.findIndex(x => x.Row == arr.Row);
        childrenIndex = index + 1;
        if ($scope.groupOfCheckboxes[childrenIndex] !== undefined) {
            $scope.groupOfCheckboxes[childrenIndex].RowValues.forEach(e => {
                e.isActive = c;
            })
        };
    }
    $scope.setBinary = function (id) {
        $scope.groupOfCheckboxes.forEach(e => {
            e.RowValues.forEach(item => {
                if (item.td == id) $scope.setActivePrevNext(e);
            })
        });
    }

Answer №1

Instead of trying the logic from your JSFiddle, I found inspiration in this answer: Understanding a recursive directive in AngularJS

For a detailed explanation of the logic, please refer to the answers provided in the link above. To make it work for my case, I had to include event $emit and $broadcast to update parent and child scopes accordingly.

var module = angular.module('myapp', []);

module.controller("TreeCtrl", function($scope) {
  $scope.treeFamily = {
    name: "1",
    children: [{
      name: "2",
      children: [......]
    }];
  };
});

module.directive("tree", function($compile) {
  return {
    restrict: "E",
    scope: {
      family: '='
    },
    template: '<div class="circleItem" ng-click="circleClicked()" ng-class="{highlight: isHighlighted}">{{ family.name }}</div>' +
      '<ul>' +
      '<li ng-repeat="child in family.children">' + ......
      '</ul>',
    compile: function(tElement, tAttr) {......},
    controller: function($scope) {
      $scope.$on('event:changeColorOfParents', function(event, clickedCircleNumber) {...});
      $scope.$on('event:changeColorOfChildren', function(event, clickedCircleNumber) {...});

      $scope.circleClicked = function() {...};
    }
  };
});
li {
  list-style: none;
}

tree {
  margin-left: 20px;
  display: block;
}

.circleItem {...}
.circleItem.highlight {...}
<div ng-app="myapp">
  <div ng-controller="TreeCtrl">
    <tree family="treeFamily"></tree>
  </div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

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

What is the best way to retrieve an object value within an if statement?

What can I do to ensure that the line within the if statement functions properly? const player1 = { name: "Ashley", color: "purple", isTurn: true, play: function() { if (this.isTrue) { return `this["name"] is current ...

Whenever I implement JavaScript validation on my HTML page, it causes the page to become un

Whenever I try to enter more than 30 to 40 characters in the password input field on my HTML page, all web browsers become unresponsive. This issue persists even if I modify the minimum length and other requirements to 50. I am new to JavaScript. <!D ...

Issue with offset calculation in bootstrap table occurs when the bootstrap-table is closed and the window is resized

In a recent project, I utilized the bootstrap table. However, upon closing the bootstrap table with the following script: $(document).ready(function () { $(".removetable").click(function (e) { $(".table-aria").remove(); ...

The Redux state fails to start with the default initial state

I'm a newcomer to react-redux. In my reducer, I have the following structure: const initialState = { Low: [ { id: 0, technologyId: 0, technology: '', type: '', ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...

Prevent the Swiper slider from autoplaying while a video is being played, and automatically move to the next slide once the video is paused or

<div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video-js id="6304418462001" class="overlayVideo" data-account= ...

A solution for managing MUI data grid rows and columns using useRef to prevent infinite loops when handling onSortModelChange

I am encountering a similar issue as described in the question below. A suggestion was given to utilize useRef to encapsulate rows and columns and access its .current value. How can I implement this solution?? Material-UI Data Grid onSortModelChange Causi ...

Angular Typescript Filter failing to connect with service injection

I am having trouble accessing the Constant app within a filter in Angular TypeScript. How can I successfully access a service inside a filter? Module App.Filter { import Shared = Core.Shared; export class MilestoneStatusFilter123 { static $inject = ...

Creating a new array in Vue.js by filtering the results of a promise iteration

Is there a way to use the splice method to insert promise values from an old array into a new one for vue reactivity? I'm encountering an issue where the newArray remains empty and does not receive any values. Check out this link for more information. ...

What are some ways to prevent sorting and dragging of an element within ul lists?

A list styled with bullets contains various items. It is important that the last item in the list remains in a fixed position. I attempted to disable sorting using the cancel option of the .sortable() method, but it only prevented dragging without disablin ...

Finding the index of a nested div element with a click event using jQuery

I'm currently working on a click event to retrieve the index of the outermost parent div, but I'm facing some difficulties in getting it to work. Here is a snippet showcasing a list of several divs: <div class="owl-item"> <div class= ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

List the properties that the arguments object supports

During a NodeJS interview, I was presented with the following question: What properties are supported by the arguments object? a) caller b) callee c) length d) All Upon researching, I discovered that all 3 mentioned properties are supposed to be present ...

Navigating JSONP using jQuery

I'm encountering an issue where I can see the correct response in Firebug, but I'm unable to access the data it returns. I need some guidance on how to achieve this. Specifically, I'm attempting to place the timestamp of an entry into a div ...

Understanding the significance of underscores in JavaScript strings

Some places mention using _() around strings like _('some string'). For instance, in a desktop program with these imports: const Applet = imports.ui.applet; const St = imports.gi.St; const Gdk = imports.gi.Gdk; const Gtk = imports.gi.Gtk; const ...

Difficulty in accurately retrieving the value in a PHP echo statement using jQuery

$id = "123"; When on the page book.php, $id is passed to an external jquery-book.php file. <script type="text/javascript"> var id = '<?php echo $id; ?>'; </script> <script type="text/javascript" src="jquery-book.php"& ...

Is there a way to automatically insert page numbers into every internal link on an HTML page?

When in print mode, I want to display links like this: <a href="#targetPage">link</a> but I'd prefer them to appear as: <a href="#targetPage">link (page 11)</a> (assuming the target page is on page 11 in the print preview). ...

Is there a way to update specific content within a view in express.js without having to re-render the entire view?

I'm in the process of creating a calendar that allows users to click on dates, triggering a popup window displaying events for that specific date. The challenge lies in not knowing which date the user will click on prior to rendering, making it diffic ...

Ensuring the cookie remains active throughout various subdomains

After implementing code to set a cookie on example.com, I noticed an issue with it carrying over to the subdomain dogs.example.com. <script> document.cookie="cid1={{utm_campaign}}; path=/;" </script> The {{}} is part of Google-Tag-Manager s ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...