AngularJS Kids Filter

I am a beginner in AngularJS and I am attempting to create a tree data structure using filters in AngularJS.

Below is the HTML code snippet:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>

    <body ng-app="myApp">
        <div  ng-controller="myCtrl">
            <table class="table table-condensed">
                <thead>
                    <tr>
                        <th ng-repeat="x in tableHeaders">
                            <label>[[ x.name ]]</label> 
                        </th>
                        <th class="text-center"><label>Options</label></th>
                     </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in items | childrenFilter" ng-if="!noRecord">
                        <td>[[ x.name ]]</td>
                        <td>[[ x.code ]]</td>
                        <td class="text-center">
                            <a href="#/update/[[ x.id ]]"><span class="glyphicon glyphicon-pencil" data-toggle="tooltip" title="Update"></span></a>
                            <span class="glyphicon glyphicon-remove" data-toggle="tooltip" title="Delete"></span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>

And here is the JavaScript code section:

app = angular.module('myApp', []);
app.config(function($interpolateProvider, $httpProvider) {
    // Change template tags
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

app.filter('childrenFilter', function(){
    return function (items){
        nodeKey = 'children';

        for (var i = 0; i < items.length; i++) {
            if(nodeKey in items[i]){
                x = items[i];
                while(nodeKey in x){
                    x = x[nodeKey];
                    for(y=0;y<x.length;y++){
                        x = x[y];
                    }
                }
            }
        }
    return items;
    }
});



app.controller('myCtrl', function($scope){
    $scope.items = [
        {
            "name": "Tankers",
            "code": "TANK",
            "id": 1,
            "children": [
                {
                    "name": "Oiler",
                    "code": "OIL",
                    "id": 2
                },
                {
                    "name": "Chemical",
                    "code": "CHEM",
                    "id": 3,
                    "children": [
                        {
                            "name": "Production",
                            "code": "PROD",
                            "id": 6
                        }
                    ]
                }
            ]
        },
        {
            "name": "Bulker",
            "code": "BULK",
            "id": 4,
            "children": [
                {
                    "name": "Logger",
                    "code": "LOG",
                    "id": 5
                }
            ]
        },
        {
            "name": "Sterilized",
            "code": "STER",
            "id": 21
        }
    ];

    $scope.tableHeaders = [
        {'name': 'Name.'},
        {'name': 'Code'},
        {'name': 'Updated By'},
        {'name': 'Date Updated'},
    ];
});

To be frank, I'm currently facing some challenges with this task and my goal is to achieve something similar to the image provided below, where all the children of a specific object are displayed indented and can be toggled:

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

Answer №1

It might be beneficial for you to conduct a more thorough search on StackOverflow next time. I came across a relevant question that addresses what you are attempting to accomplish: the issue and a helpful plnkr. Using filters might not be suitable for your particular scenario.

In JavaScript, when defining an object, there is no need to enclose the property names in quotes: name, code, id, children, etc.

var data = [{
    name: "Tankers",
    code: "TANK",
    id: 1,
    children: [ 
        // ...
    ],
    // ...
}];

Additonally, in AngularJS, you can utilize ng-repeat not only with objects but also with arrays:

$scope.tableHeader = ["Name", "Code", "Updated By", "Date Updated", "Options"];

Then:

<th ng-repeat="header in tableHeader">{{header}}</th>

Check out this fiddle containing some corrections to your code.

There is a wide range of modules available for AngularJS offering various functionalities. For instance, consider exploring UI Grid as it may assist in achieving your goals.

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

Using jQuery, you can easily pass an array in an AJAX request

I am working on a form that has multiple identical fields: <input type="text" id="qte" value="" name="qte[]"> How can I pass the array to my file processing? I have observed that the array sent via ajax is converted into a string. $("#form_comman ...

Is it possible to modify a nested h2 element using getElementsByTagName?

Looking to dynamically change the text of an h2 element nested within a div using JavaScript? No problem! Let's dive into how we can achieve this without altering the HTML file directly. Here's the HTML structure we're working with: <div ...

The "Array" function is not functioning correctly when used in an EaselJS CreateJS Container

I am currently developing a semi-OOP game and utilizing EaselJS as my chosen library. While I have made significant progress, I have encountered a persistent issue that is proving to be quite troublesome. The problem arises when I attempt to render out m ...

Manipulating Images with jQuery: Adding and Removing Images Without Affecting Text

Below is the code I'm working with: <input type = checkbox id = "purple" name = "box" > Purple </input> <div id = birdcage></div> This is the JavaScript section: $("#purple").click(function(){ if ($("#purple").is(":chec ...

What is a more sophisticated approach to adding css to "every element except this one"?

I am currently using html/jQuery to create tabbed navigation on my website. I have managed to make the selected tab appear active by adding a CSS class "active" and changing the previous tabs to have an "inactive" class. In order to achieve this, I have in ...

Function for Sorting Including Children

I have a function that sorts divs numerically by class, but it doesn't consider children when grabbing the data. Here is the current function: $(document).ready(function () { var sortedDivs = $(".frame").find("div").toArray().sort(sorter); $.each ...

Construct a new array within a JavaScript constructor function

I have been working on setting up a constructor and trying to initialize an array inside the object that will be created. This specific array is meant to hold multiple objects. function Cluster3DObject(name){ this.name = name; ...

Unable to persist the $rootScope value upon refreshing the page

Recently, I started working with angularJS on a project that involves switching between multiple languages. However, I encountered an issue where after changing the language and refreshing the page, it reverts back to the default language (English). Can an ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

Disable the javascript link on small devices

I currently have a javascript link (Trustwave) on my desktop website theme that I need to deactivate when viewed on mobile devices: Located in footer.tpl: <div style="position:absolute; margin-left:100px; margin-top:50px"> <script type="text/j ...

JavaScript's menu button has a callback function assigned to it

The definition can be found below. var CMenu = cc.Sprite.extend({ onClickCallback: null, onClick: function (callback) { this.onClickCallback = callback; }, handleTouches: function (touch, evt) { (this.hovered && this.onClickCallback) &am ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

What is the best way to display an AngularJS expression using a ternary operator?

Can AngularJS expressions be shown in a ternary operator? If so, can someone please provide guidance on how to achieve this? Thank you in advance. I have attempted the following, but it is not working as expected: {{ jdFile ? "Job Description File : {{fi ...

Attempting to create a JavaScript class within an HTML document

Having an issue with instantiating a JavaScript class in a separate HTML file. The JavaScript class looks like this: class Puzzle { constructor(fenStart, pgnEnd) { this.fenStart = fenStart; this.pgnEnd = pgnEnd; } } module.exports = Puzzle; ...

Event handling in Node.js can sometimes result in throwing exceptions

I need advice on how to handle errors or return values from an event in my code. Here is what it looks like: _initConnection(){ try{ const errorValidation = this.errorValidation const HOST = "192.168.2.32" ...

Creating a secure ZIP file with password protection using node.js

Currently, I am faced with the challenge of creating a ZIP file in node.js with password protection. Despite using the "node-zip" module for this task, it lacks the functionality to provide password protection: var zip = new require('node-zip') ...

Develop a fresh button using either JavaScript or PHP

I have designed a mini cart (drop down) on my WordPress site with different styles for when there are products and when empty. To enhance the design, I have utilized CSS pseudo elements before and after to add content dynamically. Is it possible to includ ...

Conceal the vertical scrollbar on a webpage effortlessly using jQuery or JavaScript when opening a popup page

When I click on the <a>click me</a> tag, the popup window loads. However, during this time, the vertical scroll bar on the background page is visible. How can I hide it while my popup is loading and make it visible again when the popup closes? ...

Unable to maintain sequential IDs for textboxes using Javascript or JQuery

I am encountering a problem involving the addition and deletion of multiple text boxes using buttons. The issue lies in maintaining sequential IDs for each textbox. Below is an explanation of my code: <div class="form-group" id="intro-box"> < ...

An efficient method for changing the letter case of object variables

My current task involves handling a relatively large JavaScript object with 50 keys retrieved from an API. I need to remap the variable naming convention to fit our code's variable convention. At the moment, my approach looks like this: let newObject ...