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

Ensure the detection of 404 error status using jQuery

My current approach involves using this code snippet to retrieve data from Twitter through its API: $.ajax({ url : apiUrl, cache : false, crossDomain: true, dataType: "jsonp", success : f ...

Troubleshooting problem with Angular4's HTTP requests

While working on my Angular 4 application, I am creating an oath guard service to check the validity of tokens. If the token is not valid, I want the user to log in again. Below are the functions I have implemented for this purpose: isLogedIn(){ ret ...

Counting JSON elements in Vue.js with Laravel

I am struggling to figure out how to display the number of tasks elements in JSON format. My goal is to have something similar to this: Tasks to do 2/12 (where 2 - tasks with flag 1, 12 - all tasks) I attempted to use the length function but encountered ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

optimal application of css with jquery

I have a question about using jQuery to set the padding of a class or id. I am able to successfully change the height of an element with this code: $('.menu').css({ height: '90px' }); But now, I need to apply a specific CSS rule in jQ ...

Add HTML to a div element using jQuery when content is replicated through JavaScript

I have encountered an issue while appending HTML from a dynamically created div using JavaScript. The problem arises when I try to append the HTML multiple times - each time it adds the content twice, thrice, and so on. This is possibly happening because i ...

Tips for updating JSON values using a list of items correlating to the specified key

Is there a way to update the values of blookup in json_object by matching them with blookup_values based on their ID's? I attempted the code below, where I removed the ID's that are not present in json_object['blookup']. Unfortunately, ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

Error encountered: Jquery counter plugin Uncaught TypeError

I am attempting to incorporate the JQuery Counter Plugin into my project, but I keep encountering an error: dashboard:694 Uncaught TypeError: $(...).counterUp is not a function <!DOCTYPE html> <html lang="en"> <head> <script src ...

Sorting an array based on shortest distance in Javascript - A step-by-step guide

I need to organize an array so that each element is in the closest proximity to its previous location. The array looks like this: locations=[{"loc1",lat,long},{"loc2",lat,long},{"loc3",lat,long},{"loc4",lat,long},{"loc5",lat,long}] Here's the funct ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

Tabulating with jQuery Arrays

I am facing an issue when trying to perform calculations with certain numbers. Here is the specific code snippet causing trouble: for (var key in week_total) { $("." + key).html(week_total[key]); } After running this code, I keep getting a value of N ...

What is the appropriate response to send to the user in a web application?

I am currently developing a web application that utilizes AngularJS for the frontend, a REST API, and MongoDB as the backend, all powered by Node.js. Background to the challenge: One key requirement is to authenticate users using token-based authenticati ...

Dynamic encoding/decoding operations

Utilizing Spring MVC and Jackson, I manage the API for an application. Here's my challenge - we need to serialize the Person class in two different ways: @Entity Order{ String id; String name; String address; List<Items> items; ...

Storing JSON data in a Postgres database using Elixir and Phoenix

I have searched extensively for solutions to this problem. Utilizing the phx.gen generator, I created some CRUD functionalities. My goal is to establish repositories in my database and store GitHub activity within them. Here is my migration: def change ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...

What are the steps to develop an ElectronJS application that displays "Hello world!" in the console after a button click?

Can anyone offer a helping hand? From the depths of imagination to the realms never before conceived by humans. Check out this HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hell ...

Is there a way to incorporate multiple rules from data into a text component using Vuetify?

I'm looking to establish specific rules within a mixin for my components. Allow me to provide a straightforward example of my request: Example Link The code snippet: <v-text-field :rules="[nbRules, requiredRules]" outlined v-model="name" label ...