A guide on displaying a JSON object using the ng-repeat directive

Looking to create a dynamic treeview menu with angularJS? Wondering how to achieve the desired results using a controller ($scope.results) and JSON data? Check out the code snippet below for an example of how to structure your treeview:

<ul>
   <li class="folder"><span>Pages</span>
     <ul>
       <li class="file"><span>page1</span></li>
       <li class="file"><span>page2</span></li>
     </ul>
   </li>
   <li class="folder"><span>TestSuites</span>
     <ul>
       <li class="file"><span>TestSuites1</span></li>
     </ul>
   </li>
</ul>

JSON data:

{
    "result": [
        {
            "@type": "d",
            "@rid": "#-2:1",
            "@version": 0,
            "name": "pg3"
        },
        {
            "@type": "d",
            "@rid": "#-2:2",
            "@version": 0,
            "name": "pg3"
        },
        {
            "@type": "d",
            "@rid": "#-2:3",
            "@version": 0,
            "name": "pg3"
        }
    ],
    "notification": "Query executed in 0.023 sec. Returned 3 record(s)"
}

Controller setup:

vController.controller('v-PagesController', [
                '$scope',
                '$q',
                'vRESTService',
                function($scope, $q, vRESTService) {

                    vRESTService.getPages().then(
                            function(results) {
                                $scope.results = results;
                                console.log(results);
                              }, 
                            function() {
                                console.log(Error);
                            });
                }               
        ]); 

Answer №1

To retrieve data from a JSON file using AngularJS, you can utilize the $http.get method in your JavaScript file. Here is an example:

JavaScript File
$http.get('.json').success(function(data) {
    $scope.name = name;
});

HTML File
<table>
   <tr ng-repeat="item in items">
      <td>{{item.Name}}</td>
   </tr>
</table>

Answer №2

Presenting only the pages part since you mentioned that the json does not yet contain the testsuites:

Update your controller to assign results to a scope property:

vRESTService.getPages().then(
   function(results) {
      console.log(results);
      $scope.results = results;             
   }

Here is how your view should look like:

<ul>
   <li class="folder"><span>Pages</span>
     <ul>
       <li class="file" ng-repeat="page in results.result"><span>{{page.name}}</span></li>
     </ul>
   </li>
</ul>

http://plnkr.co/edit/mKLTxwskjPECkQUCsV05?p=preview

I suggest updating your json to include a pages property and a testSuites property:

{
  "pages": [
    {
        "@type": "d",
        "@rid": "#-2:1",
        "@version": 0,
        "name": "pg3"
    },
    {
        "@type": "d",
        "@rid": "#-2:2",
        "@version": 0,
        "name": "pg3"
    },
    {
        "@type": "d",
        "@rid": "#-2:3",
        "@version": 0,
        "name": "pg3"
    }
  ],
  "testSuites": [
    {
        "name": "TestSuites1"
    }
  ],
  "notification": "Query executed in 0.023 sec. Returned 3 record(s)"
}

Your updated view would be:

<ul>
   <li class="folder"><span>Pages</span>
     <ul>
       <li class="file" ng-repeat="page in results.pages"><span>{{page.name}}</span></li>
     </ul>
   </li>
   <li class="folder"><span>TestSuites</span>
     <ul>
       <li class="file" ng-repeat="testSuite in results.testSuites"><span>{{testSuite.name}}</span></li>
     </ul>
   </li>
</ul>

http://plnkr.co/edit/dL2OGTkiEOSzmK0O1pux?p=preview

Answer №3

In AngularJS, you can utilize the $http.get method to retrieve JSON files. Once you have received the data in the response, store it within a $scope variable in your controller. After that, you can use ng-repeat to display the data. Take a look at this example for more information:

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

Upon attempting to launch an Android app, a blank white screen remains stagnant with no visible content displayed

After developing an Android application using Apache Cordova with AngularJS, I encountered a problem when deploying it to the client. The app works fine on my mobile when I build and deploy the apk, but on the client's device, it only displays a white ...

Strategies for positioning identical Highcharts series next to one another

I am currently utilizing highcharts to create column charts. My column chart consists of multiple series, structured like this: Here is the code I am working with: $(function () { var chart; $(document).ready(function() { ...

Automatically open the first panel of the Jquery Accordion

Is there a way to automatically have the first panel in my JQuery accordion open when all panels are initially closed? Here is the HTML code for my accordion: <div class="accordionx"> <div class="acitemx"> <h3>First Panel</h3> ...

Link the <select> element with ng-options and ng-model, ensuring that the model contains a composite key

I am facing a challenge with my Angular service that retrieves a list of objects with a composite key comprising two parts. I am struggling to write the bindings in a way that properly re-binds existing data. Below is my current attempt: angular.module( ...

"An issue arises when using req.body and res.render as the values retrieved are

Encountering an unusual problem - when using req.body to transmit form input to another page, the data is properly displayed when a single word is used in the input field (e.g. "FullName"). However, when there is a space, such as in the example "Full Name" ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

The API for /api/addproducts has been resolved without a response being sent, potentially causing delays in processing requests

A response was not sent for the /api/addproducts API, which can lead to delays in processing requests. Below is the code for the add product API that I have been working on: I've debugged it using the console, but I'm still struggling to find t ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

Adding / Deleting a Row in a sequence of floated divs

I have a group of div elements arranged side by side with the float:left style as shown below: <div id="container"> <div id=0" style="float:left">> Stuff </div> <div id=1" style="float:left">> Stuff </div> < ...

Struggling to get the findAndModify or Update functions to work properly in MongoDB. Despite fetching the desired data from my ajax call, I am unable to make any changes in the database

Here is the ajax code snippet: $(function () { $("#upvoteClick").click(function () { $.ajax({ type:"POST", data: {upvote: 2}, dataType: 'json', url:"http://localhost:9000/api/upvote" }).success(functi ...

Display a helpful tooltip when hovering over elements with the use of d3-tip.js

Is it possible to display a tooltip when hovering over existing SVG elements? In this example, the elements are created during data binding. However, in my case, the circles already exist in the DOM and I need to select them right after selectedElms.enter ...

Unable to make an AJAX call to a Spring controller

I am currently attempting to make an ajax call to a Spring controller, but I am encountering an Error 405 stating "Request method 'POST' not supported." I have included my code below and would appreciate any suggestions on how to resolve this iss ...

What is the best way to implement auto-saving functionality for multiple form fields in a React application?

Whenever I make changes to the first and second columns of an item in a text field, the onBlur event triggers an auto-save. This results in the entire row being reloaded due to the update caused by the first column's save. Is there a way to prevent t ...

AngularJS field array

Is it possible to create an array that contains references to the fields in a form (such as input, textarea, etc.) and then run a function on them in my code, like addClass()? To clarify my objective - I am looking to add a red border color to any invalid ...

dart, setting the root directory for web application

I'm looking to include some sample websites in my web framework package. Currently, the sites work fine when running them as Dart-only implementations, but if I need to compile them to JavaScript, I have to manually move the subfolder from my package& ...

Enhancing Form Validation with Jquery: SSN Pattern Matching, Input Masking, and Conditional Validation

Struggling with getting the Jquery Validation to cooperate with specific rules. The SSN field is masked with SSN format, and I need the validation to prevent submission unless it's a complete SSN. There's a regex function that rejects non-SSNs, ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

Using the ui-router to repeatedly call an AngualrJS directive

I've encountered an issue with my HTML audio player in AngularJS. When the page is refreshed, everything works perfectly - I can set the source and play audio without any problems. However, if I navigate to another state in the app and then try to loa ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

The d3.select function is failing to update the chart on the website

I am facing a challenge in updating data in a d3 chart with the click on an HTML object #id. After successfully coding it in jsfiddle, I encountered issues when implementing it on a web page. The scenario involves a simple leaflet map where the chart is d ...