Showing JSON data in AngularJS

I need help with AngularJS to display JSON output. Is using gridOptions the best approach for this? I'm trying to print labels starting from the root in reverse order - label/parent's label/parent's parent's label/...

   {  
   artifactId:"6450",
   classificationId:6451,
   id:3276,
   hierarchyId:"lp",
   label:"Authorization",
   nodeId:"84",
   parent:{  
      id:3275,
      hierarchyId:"lp",
      label:"Authorize",
      nodeId:"83",
      createdBy:"INITIAL-LOAD",
      createdOn:"2014-09-12T16:21:23Z",
      updatedBy:"INITIAL-LOAD",
      updatedOn:"2014-09-12T16:21:23Z",
      parent:{  
         id:3193,
         hierarchyId:"lp",
         label:"Actions & Verbs",
         nodeId:"1",
         createdBy:"INITIAL-LOAD",
         createdOn:"2014-09-12T16:21:17Z",
         updatedBy:"INITIAL-LOAD",
         updatedOn:"2014-09-12T16:21:17Z",
         parent:{  
            id:3192,
            hierarchyId:"lp",
            label:"root",
            nodeId:"13190",
            createdBy:"INITIAL-LOAD",
            createdOn:"2014-09-12T16:21:14Z",
            updatedBy:"INITIAL-LOAD",
            updatedOn:"2014-09-12T16:21:14Z"
         }
      }
   },
   parentNodeId:"83",
   createdBy:"INITIAL-LOAD",
   createdOn:"2014-09-12T16:21:23Z",
   updatedBy:"INITIAL-LOAD",
   updatedOn:"2014-09-12T16:21:23Z"
},
{  
   artifactId:"6450",
   classificationId:6452,
   id:3280,
   hierarchyId:"lp",
   label:"Licensee",
   nodeId:"88",
   parent:{  
      id:3276,
      hierarchyId:"lp",
      label:"Authorization",
      nodeId:"84",
      createdBy:"INITIAL-LOAD",
      createdOn:"2014-09-12T16:21:23Z",
      updatedBy:"INITIAL-LOAD",
      updatedOn:"2014-09-12T16:21:23Z",
      parent:{  
         id:3275,
         hierarchyId:"lp",
         label:"Authorize",
         nodeId:"83",
         createdBy:"INITIAL-LOAD",
         createdOn:"2014-09-12T16:21:23Z",
         updatedBy:"INITIAL-LOAD",
         updatedOn:"2014-09-12T16:21:23Z",
         parent:{  
            id:3193,
            hierarchyId:"lp",
            label:"Actions & Verbs",
            nodeId:"1",
            createdBy:"INITIAL-LOAD",
            createdOn:"2014-09-12T16:21:17Z",
            updatedBy:"INITIAL-LOAD",
            updatedOn:"2014-09-12T16:21:17Z",
            parent:{  
               id:3192,
               hierarchyId:"lp",
               label:"root",
               nodeId:"13190",
               createdBy:"INITIAL-LOAD",
               createdOn:"2014-09-12T16:21:14Z",
               updatedBy:"INITIAL-LOAD",
               updatedOn:"2014-09-12T16:21:14Z"
            }
         }
      }
   },
   parentNodeId:"84",
   createdBy:"INITIAL-LOAD",
   createdOn:"2014-09-12T16:21:23Z",
   updatedBy:"INITIAL-LOAD",
   updatedOn:"2014-09-12T16:21:23Z"
},

Currently, my table structure doesn't seem right:

<table>
 <tr ng-repeat='label in labels'> 
<td> label.label </td>
<td> label.parent.label</td>
<td> label.parent.parent.label</td>
</tr>
</table>

How can I display all the labels up to the root in reverse order? In this case, it should be Root/Action&verbs/Authorize/Authorization.

Answer №1

To simplify the process of extracting labels from a nested object tree, you can create a custom scope function. This function will iterate through the object tree and generate an array of labels for each label object:

$scope.extractLabels = function (labelObj){
    var labels = [];
    while (labelObj) {
        labels.push(labelObj.label);
        labelObj = labelObj.parent;
    }
    labels = labels.reverse();
    return labels;
};

Essentially, by using this scope method on each label object with parent references, we can easily retrieve an array of labels.

Check out this example on jsFiddle

Answer №2

Have you ever seen a JSON structure like this before? It's quite intriguing to showcase, even though it may not be commonly used.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>!!!</title>
    <style type="text/css">
        td{
            border: 2px dotted green;
            padding: 4px;
            background-color: #aaa;
        }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
</head>
<body ng-app="MonApp">
    <div ng-controller="CommentsCtrl">
        <!-- all elements in comments ||| ng-repeat do foreach -->
        <table>
             <tr ng-repeat='label in labels'> 
                <td> {{label.label}} </td>
                <td> {{label.parent.label}}</td>
                <td> {{label.parent.parent.label}}</td>
            </tr>
        </table>

    </div>  


    <script>
        // create a object for using angular in this body.document (body ng-app="MonApp")
        var app = angular.module('MonApp', []);
        // create controller    
        app.controller('CommentsCtrl', function($scope){
        // create or get json with some name, here "comments"
        $scope.labels = [
            {
                artifactId: "6450",
                classificationId: 6451,
                id: 3276,
                hierarchyId: "lp",
                label: "Authorization",
                nodeId: "84",
                parent: {
                    id: 3275,
                    hierarchyId: "lp",
                    label: "Authorize",
                    nodeId: "83",
                    createdBy: "INITIAL-LOAD",
                    createdOn: "2014-09-12T16:21:23Z",
                    updatedBy: "INITIAL-LOAD",
                    updatedOn: "2014-09-12T16:21:23Z",
                    parent: {
                        id: 3193,
                        hierarchyId: "lp",
                        label: "Actions & Verbs",
                        nodeId: "1",
                        createdBy: "INITIAL-LOAD",
                        createdOn: "2014-09-12T16:21:17Z",
                        updatedBy: "INITIAL-LOAD",
                        updatedOn: "2014-09-12T16:21:17Z",
                        parent: {
                            id: 3192,
                            hierarchyId: "lp",
                            label: "root",
                            nodeId: "13190",
                            createdBy: "INITIAL-LOAD",
                            createdOn: "2014-09-12T16:21:14Z",
                            updatedBy: "INITIAL-LOAD",
                            updatedOn: "2014-09-12T16:21:14Z"
                        }
                    }
                },
                parentNodeId: "83",
                createdBy: "INITIAL-LOAD",
                createdOn: "2014-09-12T16:21:23Z",
                updatedBy: "INITIAL-LOAD",
                updatedOn: "2014-09-12T16:21:23Z"
            },
            {
                artifactId: "6450",
                classificationId: 6452,
                id: 3280,
                hierarchyId: "lp",
                label: "Licensee",
                nodeId: "88",
                parent: {
                    id: 3276,
                    hierarchyId: "lp",
                    label: "Authorization",
                    nodeId: "84",
                    createdBy: "INITIAL-LOAD",
                    createdOn: "2014-09-12T16:21:23Z",
                    updatedBy: "INITIAL-LOAD",
                    updatedOn: "2014-09-12T16:21:23Z",
                    parent: {
                        id: 3275,
                        hierarchyId: "lp",
                        label: "Authorize",
                        nodeId: "83",
                        createdBy: "INITIAL-LOAD",
                        createdOn: "2014-09-12T16:21:23Z",
                        updatedBy: "INITIAL-LOAD",
                        updatedOn: "2014-09-12T16:21:23Z",
                        parent: {
                            id: 3193,
                            hierarchyId: "lp",
                            label: "Actions & Verbs",
                            nodeId: "1",
                            createdBy: "INITIAL-LOAD",
                            createdOn: "2014-09-12T16:21:17Z",
                            updatedBy: "INITIAL-LOAD",
                            updatedOn: "2014-09-12T16:21:17Z",
                            parent: {
                                id: 3192,
                                hierarchyId: "lp",
                                label: "root",
                                nodeId: "13190",
                                createdBy: "INITIAL-LOAD",
                                createdOn: "2014-09-12T16:21:14Z",
                                updatedBy: "INITIAL-LOAD",
                                updatedOn: "2014-09-12T16:21:14Z"
                            }
                        }
                    }
                },
                parentNodeId: "84",
                createdBy: "INITIAL-LOAD",
                createdOn: "2014-09-12T16:21:23Z",
                updatedBy: "INITIAL-LOAD",
                updatedOn: "2014-09-12T16:21:23Z"
            }
        ];
    });

    </script>
</body>
</html>

This is what the JSON data results in:

Authorization Authorize Actions & Verbs Licensee Authorization Authorize

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

Streamline event listeners with a pair of attributes

I am working with a function that requires one parameter: function magical(element){ ... } In my project, I have multiple click handlers attached to different elements and classes that are invoking this function: $('#div1').click(function(){ ...

Utilizing AJAX in ASP.net Web API 2 to send and receive JSON data efficiently

net Web API 2. I want to send a JSON string to one of my POST functions and receive JSON back. My AJAX: $("#btnPost").click(function (event) { var sqlQ = "SELECT TOP 50 LTRIM(RTRIM(REPLACE(OID, ' ', ''))) FROM vwPS_DAT WHERE OID != & ...

The header authorization is missing in action

I am encountering an issue while trying to send a jwt token to my API. Strangely, even though I followed the instructions from an online course, the authorization header appears to be undefined and does not accept the token provided in the JSON response. ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

Jquery JSON AJAX Response Timing

I believe the key factor here is timing rather than the code itself. I am seeking advice on the best practice for obtaining a JSON response effectively. <script type="text/javascript"> $(window).load(function() { $(&apos ...

Guide to displaying a partial in the controller following an ajax request

After initiating an AJAX request to a method in my controller, I am attempting to display a partial. Below is the AJAX call I am currently using: $('.savings_link').click(function(event){ $.ajax({ type: 'GET', url: '/topi ...

Is combining form and fieldset causing issues?

My <form> for uploading an image and my <fieldset> for sending data via AJAX both work individually. However, when I try to merge them into one form, things get complicated. This is being done on a Node.JS server. Upload <form>: <for ...

Double-click required to toggle button

Here is the code snippet for controlling an LED using a web page. The script, linked to Python, effectively controls the LED. However, there is an issue where the button toggles to the right side (ON position) only after a double click. Upon first click ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

AngularJS | Using ngAnimate to Display Form Validation Errors

My form errors are currently being displayed successfully using CSS and conditional classes, but I recently discovered ng-message and ng-animate. Would it be possible to use ng-message to contain the error messages? Also, I have been unable to find any tu ...

Is it possible to install a Chrome extension specifically for YouTube on Google Chrome?

Hey, I'm trying to eliminate thumbnail images from YouTube. The code I am currently using is: while (true) { $("ytd-thumbnail").remove() } As of now, when I input this code in the console, it successfully removes all thumbnail images. However, I ...

Unable to load models in face-api.js even though attempting to infer the models

Currently, I am working on developing an application for face detection. However, I am encountering an error stating "SsdMobilenetv1 - load model before inference" despite loading the models. The Front End HTML File is being sent from the server, ...

Utilizing highcharts to visualize non-linear time data pulled from a CSV file

I am seeking guidance on implementing a simple graph based on data from a CSV file in web development. I lack experience in this area and have struggled to find a suitable example to follow. The CSV file contains data in the format of a unix timestamp, hu ...

How to retrieve distinct items from an array using Javascript

If I have the following array of objects: const arr = [{ id: 'A', version: 0, name: 'first' }, { id: 'A', version: 1, name: 'first' }, { id: 'B', version: 0, name: 'second&apo ...

Experience the quick sort programming algorithm in action using Vue.js without the hassle of dealing with Promises

I am currently experimenting with the quicksort algorithm visualization using Vue.js for self-educational purposes. However, I am facing some difficulties with async/await implementation. Although array filling and shuffling seem to work fine (although I a ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

Encountering difficulty in assigning the desired value to the select box

// updating the subType value in the controller $scope.newEngagement.subType = 3; // creating a list of engagement subTypes $scope.engagementSubTypeList = [ { "subTypeId": 1, "subTypeName": "value1" }, { "subTypeId": 2, "subTypeName": "value2" }, { " ...

How to align the markup of a dynamic directive with its host in Angular?

Introducing a simple directive called [popover], its main purpose is to dynamically inject a component (as a sibling). Implementation example: @Component({ selector: 'my-app', template: ` <div> <button popover>Popover ...