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

Grunt: Can you explain the concept of recursive templates?

Hey there, I'm new to using Grunt and I've run into a puzzling issue with recursive templates. Let me provide you with a concrete and straightforward example: var path = require('path'); module.exports = function(grunt) { grunt.init ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

Using a function to send multiple child data in Firebase

I am trying to figure out how to save data to a Firebase multi-child node structure: --Events ----Races -------Participants Below is some dummy data example that represents the type of data I need to store in Firebase: var dummyData = [ { ...

CSS struggles after implementing conditional checks in return statement for an unordered list

I'm encountering a CSS issue with the header section. When I include the following code snippet in my code to display a tab based on a condition, the entire header list doesn't appear in a single horizontal line: <div> {isAdmin(user) ? ...

Enhancing Angular's templates and handling cache invalidation

I have encountered a dilemma in my Angular1 project where changes made to an html template are not immediately visible to users without performing a hard refresh. Ideally, I would like to implement a cache service that checks for a timestamp and invalidate ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Is there a viable substitute for websockets that can be utilized on shared hosting platforms?

Are there any viable alternatives for websockets that can be used with shared hosting? While I'm aware of node.js, socket.io, and Express.js, I'm unable to use them in a shared hosting environment. If there are other options available for creatin ...

What is the best way to manage DOM modifications in a responsive design layout?

Developing a responsive website with only one breakpoint can be challenging, especially when restructuring the DOM to accommodate different screen sizes. It's important to consider not just CSS and media queries, but also how the elements are arranged ...

Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page: import { useRouter } from "next/router"; export default function Daily({ data }) { let router = useRouter() const { slug } = router.query; return slug; } And display on the page 60d6180ea9284106a4fd8441 ...

Is it possible to use Javascript to gradually fade in text, one word at a time, with multiple divs instead of just one?

I am attempting to gradually fade in individual words from a div. While the code below works fine for a single div, it does not execute sequentially when multiple divs are involved. Here is the fiddle : http://jsfiddle.net/zlud/6czap/110/ Can anyone spot ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

I am encountering an issue with this code. The objective is to determine the frequency at which a specific word appears in the provided paragraph

function processWords(){ text = document.getElementById("inputText").value; text = text.replace(/(^\s*)|(\s*$)/gi,""); text = text.replace(/[ ]{2,}/gi," "); text = text.replace(/\n /,"&bso ...

Show the contents of a JSON file using Vue

I have a JSON file containing some data that needs to be fetched and displayed in a component. In the actions of my Vuex store, I've implemented: async getTodos (context) { const todos = [] const response = await fetch('../../data/todos.jso ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

The jqGrid displays a plus sign even when the subgrid is empty while using XML

I am utilizing jqGrid to display data with a subgrid in XML format. $("#UDFs").jqGrid({ ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' }, datatype: 'xmlstring', datastr: data, xmlReader: { root: "Respo ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

Tips for bringing in an npm package in JavaScript stimulus

Looking to utilize the imageToZ64() function within the zpl-image module. After installing it with: npm install zpl-image I attempted importing it using: import './../../../node_modules/zpl-image'; However, when trying to use the function like ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

What is the best way to implement JQuery in order to trigger an event in a text box whenever the user hits the "enter

Also, refrain from submitting the form if the user hits enter in THAT PARTICULAR input field. ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...