Reading JSON files in AngularJS is a common practice among developers

Creating a dynamic tree using JSON is a common task in AngularJS. To achieve this, you can store your JSON data in a separate file and then read it externally. Here's an example of how you can do this:

Sample Controller Code:


$scope.myjson = {       
    "option1": [
        {   
            "child":[{"label":"Test1" },{"label":"Test2"}],
            "id": "option1"

        }
    ],

    "option2": [
        {   
            "child":[{"label":"Test1.1",}],
            "id": "option2"
        }
    ],
   // Add more options as needed...
}

Reading JSON Array (In Controller):


angular.forEach($scope.myjson, function(value, key) 
{
    if (key === 'option1') 
    {
        for(var t=0; t < $scope.myjson[key][0].child.length; t++)
        {
            // Perform operations
        }
     }
});

If you want to call a JSON file externally to create the tree, you can make use of AngularJS's built-in functions. By using services like $http or $resource, you can easily fetch the JSON file and incorporate it into your tree creation logic.

Answer №1

Working with JSON data in Angular using $http is relatively simple. Remember that $http returns a promise, which needs to be resolved before further processing.

Below is an example code snippet:

$http.get('assets/messages.json').then(function (data) {
            /** process the retrieved data **/
});

Answer №2

Click here for an in-depth tutorial on solving your issue. Feel free to customize it to suit your needs.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.example.com/customers.php")
    .success(function(response) {$scope.names = response.records;});
});
</script>

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

Utilizing JQuery Definitions for File Upload in Typescript

I'm currently working with TypeScript and facing an issue with a file upload form. However, when I try to access the files from the input element in my TypeScript code, an error is generated. $('body').on('change', '#upload_b ...

Is it possible to modify this jquery keyboard navigation to accommodate different tags and additional keyboard functions?

I am currently in the process of developing a basic website featuring images arranged vertically on the page. My goal is to enable smooth scrolling between these images using the keyboard arrow keys. With the assistance of this forum, I have been provided ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...

An easy guide to animating multiple sections of progress bars individually in Bootstrap

My Bootstrap code successfully animates a section of progress bars when the user views it. However, it currently animates all progress bars on the page rather than just those in the viewed section. This means that when the user moves to another section, th ...

Leveraging vue.js props in the mounted function

In my current Vue.js project, I have encountered an issue while using props to pass a value from one component to another. The value received from the props is stored in a variable called "this.Id". I am able to display this value using an alert within the ...

Issue with React conditional display not functioning properly post user input into a form

Thank you in advance for your help. I am working on a component that displays a button based on the const results. However, I noticed that when I insert "Balaton," the button only appears after I add another character to the string. So the string becomes ...

How to display JSON images in an Android listview

I'm facing difficulty in loading images from a JSON file to the listview on my Android app Although I know that I need to use BitmapFactory.decodeStream, I am unsure about how to proceed with the implementation Below are the details of my adapter an ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

JSP Implementation of a Gravity-Driven Dynamic List

I am looking for a way to automatically populate a dropdown list within a JSP page form using values retrieved from a database query. The challenge is that only a limited number of rows are being pulled from the database based on other form inputs. I am no ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Retrieve parameter from Ajax in Laravel's controller

I'm looking to transfer the value of an id to a controller in Laravel This is my Ajax Code: $(document).ready(function () { $(document).on('click', '.brnch_clk', function () { //alert('ok') ...

The two CSS classes are styled with different border-color values, but only one is being applied correctly

My goal is to modify the border color of a textarea using jQuery. Previously, I achieved this by using .css("border-color","rgb(250,0,0)"), and it was working perfectly. However, I have now been advised against using CSS directly in JavaScript and told to ...

Deactivate and hide button that triggers modal dialog

Combining Bootstrap with AngularJS, I encounter an issue in my application where a link triggers a modal dialog using data attributes. My goal is to disable the button based on a state variable or function. The problem arises when AngularJS still executes ...

Utilizing Ajax to dynamically load files within the Django framework

My current project involves working with Django, specifically a feature that requires loading a file and displaying its content in a textarea. Instead of storing the file on the server side or in a database, I am exploring the use of AJAX to send the file ...

Issue with ajax form: success function is not functioning as intended

For my form submission, I am utilizing ajaxForm(options) to run some functions before submitting the form. Here is an example of the options that I have configured: var options = { target : '#output1', success : ...

Guidance on sharing an image on Twitter using Node.js

Every time I attempt to upload a PNG image to the Twit library in Node, an error arises. My objective is to develop a Twitter bot in Node.js that generates a random RGB colour, creates an image of this colour, and tweets it. Thanks to some assistance prov ...

React Navigation Error: navigateTo must be used within a valid router configuration

When attempting to utilize useNavigation() from react-router-dom, I encounter the following error: Error: useNavigation must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router. NavBar src/components/NavBar.js:6 3 ...

How to Load JavaScript Files into Joomla 2.5 default.php File

When creating a component in Joomla 2.5, I encountered an issue while trying to add some JavaScript code into the layout file tmpl/default.php . To include the JavaScript files, I used the following code: $document->addScript(JURI::base() . "components ...

I'm curious why one of my Material UI autocomplete components is displaying options with a blue background while the other isn't. Take a look at the code sandbox for more insight

UPDATE: Problem solved! I managed to find a solution and have updated my sandbox with the fix! REVISION: After some investigation, I have identified that the issue lies within this specific line of code in the autocomplete... isOptionEqualToValue={(option ...

The method this.$refs.myProperty.refresh cannot be invoked as it is not a valid

I have added a reference value 'callingTable' to a vue-data-table (using vuetify) like so: <v-data-table :headers="callingTableHeaders" :items="getCallingDetails" class="elevation-1" ref="callingTable&quo ...