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:

Here is the default view:

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

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:

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

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:

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

excess white space appears in the mobile version

I recently completed a website using both materializecss and bootstrap platforms. While I know this may not be the best practice, it worked for my needs. However, I am facing an issue with the mobile view. When I reduce the viewport size, a margin appear ...

Using $location in an Angular directive causes a cascade effect of repainting all other directives

I am encountering an issue with my page where multiple directives are being used: <section class="start_page page--no-vcenter"> <u-search> <u-search-form></u-search-form> <u-news-form></u-ne ...

Which javascript library provides the top-notch SVG graphics support for Internet Explorer and other web browsers?

Currently, I am developing a web application using javascript and jquery that involves drawing numerous rectangles and lines connecting them. It seems like I need to find an SVG graphics library to create lightweight components (approximately 300). The ch ...

Understanding the functionality of $exceptionHandlerIn order to fully

While exploring angularjs, I discovered a method to manage uncaught exceptions using the built-in $exceptionHandler service. As stated in the documentation, I am manually handling exceptions by incorporating try {...} - catch(e). Below is an example: try ...

The status is currently not defined when attempting to retrieve JSON data and display it on individual pages for each piece of data

I have written some code where I am trying to display the attributes of a selected product from my product page based on its ID. For example, when a product is clicked, it should redirect to a URL like /#/product/2 and display all the attributes of the pro ...

Backend undergoing fluctuations in hourly values

When passing JS dateTime to the backend using ajax(axios), I encountered a discrepancy in the timestamps. Prior to the post request, I have the following timestamp: Sun Nov 04 2018 21:53:38 GMT+0500 However, upon reaching the backend, the timestam ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

Guide to extracting and utilizing a JSON object received from the parent page

Hello, I've been searching online for quite some time and can't seem to find a solution to my question. If anyone could help, I would greatly appreciate it. Below is the code I am working with: <ion-content> ...

Issue occurs when a circle element is not following a div element on mouse

Currently, I have implemented some jQuery code that instructs a div named small-circle to track my cursor movement. I discovered how to accomplish this by referencing a thread on stack overflow. I made slight modifications to the script to suit my specifi ...

Guidelines for sending JSON Data via Request Body using jQuery

I'm not well-versed in jQuery, so consider me a beginner. Here's my code that is not correctly handling JSON data submission via Request Body. <!doctype html> <html lang="en> <head> <title>jQuery JSON Data Submission ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Looking to remove a row with php, html, and ajax?

Trying to remove a row from an HTML table has been my latest challenge while working with Materialize CSS. Here is what I have so far, where the ID corresponds to the employee ID: https://i.stack.imgur.com/rjwba.png Below is the code snippet: <?php ...

Handling a jQuery Ajax success callback when it fails

I am encountering an issue with my ajax post request where even though I have separate success, failure, and status code handlers, when the request fails with a 400 error, part of the success function is still being executed. Can someone provide insight in ...

What is the best way to store font size and background color settings in local storage?

After following the solution provided for a similar issue on SO, I am facing a problem where no changes are reflected when using the select box or color picker to modify the font size or background color. I have commented out the lines that were added in a ...

Attempting to showcase a collection of values, specifically focusing on highlighting the even numbers within the array

const sampleArray = [ 469, " " + 755, " " + 244, " " + 245, " " + 758, " " + 450, " " + 302, " " + 20, " " + 712, " " + 71, " " + 456, ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

Using $nin alongside $and in Mongoose

Implementing a filter for an admin user using mongoose operations. The user should be able to view all saved files except for those that are classified as draft files. However, the admin user should still have access to their own saved draft files. Code ...

Is it possible to use v-model on an input that is being dynamically updated by another script?

How can I retrieve the lat and lng values stored in two input fields when a user changes the marker's position on a Google map? When the user clicks to select a new place, I need to update these inputs accordingly. I attempted using v-model but it onl ...