What is the best way to connect an external JSON file to an Angular controller?

As I embark on my first Angular JS project, I find myself in need of exporting a JSON array from my controller to an external JSON file. Here is the snippet from my controller containing the JSON data:

Fantacalcio.controller('fantacalcioController', function($scope){
  $scope.myTeam = [
      {
        Player: {
          name: "Orestis",
          surname:"Karnezis"
        },
          rating: "4.91",
          team: "Udinese"
        },

    .....
        Player: {
          name: "Patrick",
          surname:"Schick"
        },
          rating: "6.97",
          position: "forward",
          team: "Sampdoria"
      }
];

});

And here is how I've set up my component:

Fantacalcio.component('table', {
    templateUrl: 'components/table.html',
    controller: 'fantacalcioController'
  });

I am now looking for guidance on how to store this JSON array in an external JSON file. I understand that I should utilize $http to make a get request, but I am unsure of how to implement it. I attempted following this solution https://docs.angularjs.org/tutorial/step_07 without success.

Any help would be greatly appreciated.

Answer №1

create in this manner:

url : '/1',
templateUrl : 'partials/1.html',
controller : function($scope, $http, $log){
  $http.get('phones/phones.json').then(function(response) {
      $scope.phones = response.data.phones;
  });
}

utilize $scope instead of self this in component or add the following code to controller "fantacalcioController"

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

ensure that the phones folder is located in your app's root directory and phones.json is inside the phones folder.

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

The tools needed for securing a web application with ExpressJS include the use of

I recently implemented an upload function using connect-form with formidable and https://github.com/ctavan/express-validator. While attempting to sanitize an image from XSS, I encountered a 'TypeError: Cannot call method 'replace' of undefin ...

Ensure that an async function's result is resolved before rendering react routes

I've been working on setting up an authentication service in my single-page application using React in the routes file. The goal is to check if a user is trying to access a private path, and verify that the token stored locally is valid. However, I&ap ...

Modify the text and purpose of the button

I have a button that I would like to customize. Here is the HTML code for the button: <button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button> The corresponding JavaScript code is as follows: var search = n ...

What is the method for displaying console.log() messages on Heroku?

Lately, I've been making efforts to troubleshoot my app using console.log() within Node.js. Despite adding numerous lines of code for debugging purposes, I have yet to find them in the heroku log no matter how many times I check. $ heroku logs -n 20 ...

The JavaScript audio is not working for the first three clicks, but starts playing smoothly from the fourth click onwards. What could be causing this issue?

$(".btn").click(function(event){ playSound(event.target.id); }); function playSound(name){ $("." + name).click(function() { new Audio("sounds/" + name + ".mp3").play(); ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Internet Explorer 8 halts the progress of the loading animated GIF

When I call an animated loading gif image on an <asp:Button> click event in the client side code, the animation stops in IE8 while the server-side code is executing. This issue does not occur in Mozilla or other browsers. The animation works fine wh ...

How to retrieve the innerWidth value using AngularJS

I am seeking a way to access the innerWidth of my browser within my controller. Although I have come across a directive that can display the width on the screen, I would prefer to have this functionality within my controller. The ng-repeat in my code relie ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

"Introducing a smooth animation effect to shift text alignment to the center

I'm currently using the code below, but I am not satisfied with the margin adjustment achieved by text-align:center;. Is there a way to smoothly transition the text alignment to center similar to how it is done in the following snippet of code? if ($ ...

Maintain the selected list item after filtering in AngularJS

I am facing an issue with highlighting selected items in a list. I have three first names: Roy, Sam, David displayed in a ul as list items. Initially, I can toggle each li on click just fine. However, after performing a search and returning to the list, th ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

send the value of a variable from a child component to its parent

I have created a typeahead component within a form component and I am trying to pass the value of the v-model from the child component to its parent. Specifically, I want to take the query model from the typeahead component and place it in the company mode ...

Automatically resetting the Redux toolkit store when navigating between pages in Next.js

I am a new Next user who has been using Redux with React for a while. However, I encountered many challenges when trying to integrate Redux with Next. I have decided to move on from this solution. store.js import { configureStore } from '@reduxjs/to ...

Is there a way to personalize cards in angular-material?

Currently, I am working on customizing angular-material cards and have run into an issue. Although I have been successful in making various adjustments, I am struggling to set the height of the cards to a specific value. For instance, I would like to creat ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Unreliable static URLs with Next.js static site generation

I've recently built a Next.js website with the following structure: - pages - articles - [slug].js - index.js - components - nav.js Within nav.js, I have set up routing for all links using next/link, including in pages/articles/[slug].j ...

View content from a text file on a webpage

Hi everyone, I could really use some assistance with a project I'm currently working on. As someone who is new to programming, I am facing a challenge. My goal is to showcase the contents of a plain text file on a webpage. This text file, titled titl ...