Store my JSON data in a separate file and then reference it in my controller

Hello, I am currently working on an AngularJS application development project. Within my JSON data, I have information structured like this:

angular.module('app', []).controller('MainController', ['$scope', function($scope) {
      $scope.cities = [{
        name: "city A",
        elements: [{
          id: 'c01',
          name: 'name1',
          price: 15,
          qte: 10
        }, {
          id: 'c02',
          name: 'name2',
          price: 18,
          qte: 11
        },
        ... (truncated for brevity)
      }];
      $scope.extractSubsities = function(itemSelected) {
        if (itemSelected && itemSelected.elements) {
          $scope.data = itemSelected.elements;
        }
      }

    });

To improve code cleanliness and adhere to best practices, I want to extract this data into a separate JSON file and call it as follows:

angular.module('app', []).controller('MainController', ['$scope', function($scope) {
      $scope.cities = /*insert method to call external JSON here*/;
      $scope.extractSubsities = function(itemSelected) {
        if (itemSelected && itemSelected.elements) {
          $scope.data = itemSelected.elements;
        }
      }

    });

Any help on achieving this would be greatly appreciated.

UPDATE

I attempted the suggestions provided in the responses but encountered issues. Here's what I did:

I set up a XAMPP web server hosting all my files

I modified my script as follows:

angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/controllers/data.json').then(function(response) {
            $scope.cities = response.data;
  });
  $scope.extractSubsities = function(itemSelected) {
    if (itemSelected && itemSelected.elements) {
        $scope.data = itemSelected.elements;
    }
  }
 }]);

Here is the content of my data.json file:

{
"data":[{
        "name": "city A",
        "elements": [{
          "id": "c01",
          "name": "name1",
          "price": "15",
          "qte": "10"
        }, 
        ... (truncated for brevity)
}

Despite these efforts, the data still fails to load. Any further assistance would be welcomed.

Answer №1

To retrieve data from an external source in JSON format, you need to use the $http service for injection. This code snippet demonstrates how to fetch data by injecting the $http service into your AngularJS controller.

angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
  $http.get('link to json').then(function(response) {
            $scope.cities = response.data;
  });
  $scope.extractSubsities = function(itemSelected) {
    if (itemSelected && itemSelected.elements) {
        $scope.data = itemSelected.elements;
    }
  }
 }]);

Answer №2

To retrieve the file, it is necessary to utilize ajax:

$http.get('file.json').then(function(response) {
    $scope.cities = response.data;
});

Answer №3

To access the data in a JSON file within your project directory, you'll first need to inject the $http service into your controller and make a GET request.

Here's an example of how your controller could be set up:

angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
    $scope.cities;
    $scope.extractSubsities = function(itemSelected) {
        if (itemSelected && itemSelected.elements) {
            $scope.data = itemSelected.elements;
        }
    }

    function getCities() {
        $http.get('/data/cities.json').then(function(response) {
            $scope.cities = response.data;
        });
    }

}]);

This assumes that your JSON file is named cities.json and is located at data/cities.json in your project structure.

If you'd like more guidance on best practices, check out John Papa's styleguide on GitHub:

Styleguide by John Papa

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

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

Troubleshooting problems with the width of a Bootstrap navbar

I'm encountering a frustrating issue with my bootstrap menu. When I include the "navbar Form" in the menu, the width of the menu extends beyond the screen width in mobile mode (when resizing the browser window or viewing on a mobile device). Interesti ...

The MySQL error wreaks havoc on the Node.js server, causing it to

Whenever there is an error or exception coming from MySQL, my nodejs server ends up crashing. This is the code snippet from my backend where I tried using if-else in the query function to handle the response, but it still crashes the server. Even with try ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

I desire to activate the textbox only when the radiobtnlist value equals 1

I am trying to disable a textbox based on the selected value of a RadioButtonList in my code. However, the functionality is not working as expected and I am unsure why. <script type="text/javascript"> $(function () { $("#RadioButton ...

Using jQuery to iterate through elements of a PHP array

I've got a PHP array that outputs like this: Array ( [0] => Array ( [title] => Much title [end] => Such end [start] => Very start ) [1] => Array ( [title] ...

Issue encountered in transmitting information from JSP to servlet

I am facing an issue with receiving data from JSP to servlet. I understand that I need to serialize this data using JSON. In my JSP, I have written the following JavaScript code: var myJSONText = JSON.stringify(items); document.getElementById('test&a ...

Exploring the ways to access inner contents of a Div element using ajax

Looking to update the SQL database with a list of variables sent from an HTML page. Some data is being sent correctly, while others are not. The list is placed in a div divided into two parts: "h1" and another "div". The header data is being sent correctly ...

What is the correct way to run javascript on a DOM element when ng-show is triggered?

For those who prefer shorter explanations, there's a TLDR at the end. Otherwise, here's a detailed breakdown. I have a form that consists of multiple inputs organized into different "pages" using ng-show. What I aim to achieve is when ng-show r ...

Tips for combining HTML and JavaScript on a WordPress site

As a WordPress developer who is still learning the ropes, I have come across a challenge with embedding html and JavaScript onto a page. Currently, I am in the process of redesigning a company website and one of the tasks involves integrating a calculator ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

The wrapAll() method can be used to wrap list items within two columns

I am looking to group multiple li elements within two div containers by using jQuery's wrapAll method. The challenge lies in the fact that these items are rendered within a single <ul> element via a CMS. Here is the current setup: <ul> ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Converting a busboy file stream into a binary object in Node.js: A step-by-step guide

Seeking assistance with image file upload functionality by integrating Express and Node.js. Currently, I am utilizing the Busboy package to receive binary data in a file format. Specifically, my inquiry revolves around understanding how to capture this bi ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

Organize data in a Vue.js table

Currently facing an issue with sorting my table in vue.js. Looking to organize the table so that campaigns with the highest spend are displayed at the top in descending order. Here is the code I'm working with: <template> <div class=" ...

Incorporating filters within ui-sref for enhanced functionality

After coming across this answer, I realized it doesn't address my specific issue. My goal is to have the complete state name generated by my filter, rather than just using the filter for state parameters. Is there a way to use a filter to generate th ...

What is the process for updating the values of Kendo Grid row elements by utilizing data from an external combobox?

I am currently working with a kendo grid that utilizes the roweditor function, allowing users to edit values of networks labeled as network1, network2, and network3 within the grid - let's refer to this as gridNetwork. On the same page, there is also ...

Generating HTML content from XML data with the help of JavaScript

Challenge: Attempting to display one question and its four corresponding answers at a time from an XML file. JavaScript code: var xmlDoc, quest, ans, i, n; xmlDoc = loadXMLDoc("questions.xml"); quest = xmlDoc.getElementsByTagName('main'); do ...

Issue with Jquery: Checkbox fails to get checked in Internet Explorer 7

Having trouble with checking a checkbox, I've attempted the following steps: $('#someId').attr('checked','checked'); $('#someId').attr('checked', true); Both of these methods are effective for I ...