AngularJS - Organize Item Hierarchy with Separate Containers for Each Group

My goal is to incorporate a $scope variable within an AngularJS controller that has the following structure:

$scope.hierarchy = {
  name: 'bob',
  selected: true,
  children: [
    { name: 'frank' },
    {
      name: 'spike',
      children: [
        { name: 'mike' },
        { name: 'ben' },
        { name: 'gloria' },
      ]
    },
    {
      name: 'lisa',
      selected: true,
      children: [
        { name: 'bobby' },
        { name: 'carol' },
        { name: 'roger' },
      ]
    },
  ]
}

The objective is to populate a template using this variable. The requirement is to display all items at one level in one box, with a new box for the children of the selected item (similar to OSX Finder's folder browsing).

Essentially, I aim to create an angular template that renders something like this:

+------+ +--------+ +-------+
| >bob | |  frank | | bobby |
+------+ |  spike | | carol |
         | >lisa  | | roger |
         +--------+ +-------+

Although it may appear straightforward, I seem to be struggling with finding the solution. Any assistance would be greatly appreciated!

Answer №1

Following the example provided by Cherniv, you can check out a functional fiddle here. By adjusting the layout as shown in the fiddle, it is evident that setting 'selected: true' on spike instead of Lisa results in correct adjustments.

Here is the HTML code:

<script type="text/ng-template"  id="tree_item_renderer.html">
    <ul>
        <li ng-repeat="data in data.children">
            {{data.name}}
            <ul>
                <span ng-switch on="data.selected">
                <div ng-switch-when="true" ng-include="'tree_item_renderer.html'">
                </li>
                </span>
            </ul>
        </li>
    </ul>
</script>

<div ng-controller="TreeController">
    <div ng-include="'tree_item_renderer.html'">
    </div>
</div>
</ul>

And here is the Javascript code:

var myApp = angular.module("myApp", []);
myApp.controller("TreeController", ['$scope', function($scope) {
    $scope.data = {
        children: [{
          name: 'bob',
          selected: true,
          children: [
            { name: 'frank' },
            {
              name: 'spike',
              children: [
                { name: 'mike' },
                { name: 'ben' },
                { name: 'gloria' },
              ]
            },
            {
              name: 'lisa',
              selected: true,
              children: [
                { name: 'bobby' },
                { name: 'carol' },
                { name: 'roger' },
              ]
            }
          ]
        }]
    }

}]);

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 FontLoader feature seems to be causing issues when integrated with Vuejs

While working on a Vue project with threejs, I encountered an error similar to the one described here. The issue arose when attempting to generate a text geometry despite confirming that the path to the typeface font is accurate and in json format. ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...

Differences between jQuery and Google Closure in terms of handling AJAX

Recently, I've been exploring the Google Closure Library for handling ajax calls. I came across an example that piqued my interest: goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // perform a cool action } els ...

The extracted text from the window appears to be blank

When attempting to enclose a selected string between two characters, I am encountering an issue. For example, when selecting 'test' and clicking on the change button, the selected text should change to 'atestb'. However, although I am a ...

The server is indicating that the validation for the user has failed due to the required field "foo" not being provided in the Node.js

An error message was received with the following details: "User validation failed: email: Path email is required., display_name: Path display_name is required." The error name returned is: ValidationError. The AJAX call code snippet is as follows: f ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Retrieve all elements from an array using jQuery

How do I extract all the elements from the array outside of the function? $.each(Basepath.Templates, function(i){ templateArray = new Array({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, descri ...

Why do React components require immutable props when values are passed by value regardless?

I am not deeply knowledgeable in JavaScript, so I have been experimenting with some code: var demo = 'test'; var obj = { x: 'abc' } function foo(str) { str += '_123'; ...

Using Javascript to access a website from a Windows Store application

Currently, I am working on a project to create a Windows store app using HTML and JavaScript. One of the key components of my app involves logging into a specific website with a username and password. Here is an example website for reference: The process ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

Enhancing code with new Javascript functionality

Currently utilizing the WordPress Contact Form 7 plugin and in need of updating my existing JavaScript code to include an onclick function and data-img attribute for checkboxes. Due to the limitations of Contact Form 7 shortcode, adding attributes beyond i ...

Ensuring the accuracy of URLs using JavaScript

I am developing a form with an input field for entering a URL and a submit button. I want to incorporate JavaScript validation to show an alert box when a correct URL is entered. Is it achievable using JavaScript? If so, can you please guide me on how to i ...

Two interdependent select fields

I am currently working on creating two select fields where, upon selecting an option in the first field, some options in the second field should be hidden. I have almost achieved this, but my script is unable to locate certain options in the first select f ...

A guide on accessing URL query parameters using AngularJS

Is it possible to extract specific URL parameters using AngularJS and then assign their values to textboxes? For instance, a sample URL would be: http://example.com/?param1=value1 I've come across examples involving $location, routing, and services ...

Prevent memory leakage by utilizing Angular's $interval feature in countdown processes

I have a controller set up to handle a countdown feature: var addzero; addzero = function(number) { if (number < 10) { return '0' + number; } return number; }; angular.module('theapp').controller('TematicCountdownCo ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Using JavaScript and jQuery to create a delay when handling input events

I am working on a project where I have an HTML table that retrieves its values from a database using jQuery Ajax. Here is an example: <div id="tableId"></div> Below is the JavaScript code: function showUser(rowsToShow) { request = $.get("s ...

Angular decode UTF8 characters with pascalprecht.translate

I'm facing issues with UTF8 characters when using SanitizeValueStrategy('sanitize'). This is necessary because the client will be editing texts in language files and may include tags like <b> or <i>... I want to rely exclusively ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...