Fetching data from a server using Angular and displaying it in controllers

I am currently working on a project where I need to retrieve JSON files and their content using a factory in AngularJS. My main goal is to make this data accessible to other controllers, but I am struggling with getting the factory to return the deityData.

Here is the code snippet that I have for the factory:

app.controller("dataContainer", function($scope,$http){

  $http.get("./data/deitys/data.json").then(function (response) {

    $scope.myData = response.data;
    for(var i = 0; i < $scope.myData["deitys"].length;i++){
        var dataString = "./data/deitys/" + $scope.myData["deitys"][i] +".json";

        $http.get(dataString).then(function (response_) {

            var deityData = response_.data;
            $scope.deitys[deityData.deityName] = deityData;
        });                                         
    }

});   

Answer №1

  1. Let's establish a specialized service for this purpose, named deityService.

    angular.service("deityService", () => {
      this.deityData = undefined;
    });
    
  2. Include deityService as a dependency in all controllers that require access to this data.

  3. Once you have retrieved the necessary data in your dataContainer controller, assign it to deityData and trigger an event to inform other controllers about its availability.

    this.deityService.deityData = fetched_data;
    this.deityService.emit("DEITY_DATA_SET");
    
  4. Register a listener in all controllers for the specified event.

    this.deityService.on("DEITY_DATA_SET",() => {
      // You can now log console.log(this.deityService.deityData);
      }
    );
    

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

Learn how to redirect pages or app folders to a subdomain using Next.js

I have been extensively searching the internet for information on this topic, but I haven't come across any relevant articles. For example, in the root of my project, there's a folder called pages with the following file structure: | 404.js ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...

The mobile screen size shortcuts are malfunctioning, while the regular links are functioning properly

ISSUE: Links in alias buttons are not working on mobile screen size, while normal links to other webpages like social media work fine. Description I created a project using an HTML, CSS, JS building tool from The project was exported and placed into a ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

How to replicate Javascript's 32-bit signed integer arithmetic in C (or Perl) with a few differences

I have encountered a discrepancy when translating simple JS code to C and/or Perl, specifically related to arithmetic operations (+ - * / << >>) on integers causing overflow. My goal is to replicate the exact behavior of JS, including handling ...

I need to inform users that this application is not accessible on devices with small screens

Showing this app on a small device is not supported, such as when the device width falls between 320px and 480px. ...

Identifying Shifts in Objects Using Angular 5

Is there a way to detect changes in an object connected to a large form? My goal is to display save/cancel buttons at the bottom of the page whenever a user makes changes to the input. One approach I considered was creating a copy of the object and using ...

Utilizing Express.js for setting up routes with a default path

In the code snippet below, I am utilizing Express.js: router = express.Router() fs.readdirSync('./controllers').forEach(function (file) { if(file.substr(-3) == '.js') { route = require('./controllers/' + file); ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

Contrast in the way an angular controller integrates $scope

I am brand new to using Angular. I have noticed two different ways of passing the $scope object to an angular controller: app.controller("myCtrl", function($scope) { ... }); app.controller('myCtrl', ['$scope', function($scope) { ... } ...

Pass data from Action Class to ajax using JSON syntax

Currently I am facing an issue while working on fullCalendar, a jQuery plugin. I am trying to populate event details from a database when the Calendar page loads, but I seem to be stuck with a silly problem that I can't figure out. $('#calendar& ...

Once an ajax request is made, scripts cease to function correctly

There is a dynamic table on a webpage that I update using ajax. The table contains checkboxes and there are scripts that utilize the checkboxes for certain functionalities, such as toggling the check/uncheck status of all checkboxes when a "Check all / Unc ...

The task "grunt-karma.js" is currently being loaded, but unfortunately an error has occurred: SyntaxError - An unexpected identifier was found

Encountering an issue when loading "grunt-karma.js" tasks while all other tasks are loading correctly. This problem started to occur after updating several dependencies, including grunt-karma and karma. Here is the section from my package.json: "grunt-ka ...

Tips for preventing automatic zoom on mobile devices

Check out this link for the test: The current layout of the site is exactly how I want it to be presented. However, I am facing an issue where if I set the viewport meta tag to <meta name="viewport" content="width=device-width, initial-scale=1"> i ...

What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method: fetch('https://foobar.com/auth', { method: 'GET', mode: 'cors', credentials: 'include', }) The server-side code in express for impl ...

Attempting to perform a second HTTP GET request on a nodejs/express backend will result in an

Utilizing the express and ftp packages, I am attempting to fetch files from an FTP server and then display them to the client via HTTP GET requests. The initial request is successful, but upon trying to make another call, I encounter the following Excepti ...

What is the ideal location to set up Content Security Policy?

I am working with an angular application that interacts with a REST API hosted on either Tomcat or Jetty, depending on the setup. The angular-app itself is deployed as a war file on the same tomcat/jetty server. In some cases, the Tomcat setup includes Ap ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

The import 'react-router' does not include an export called 'browserHistory'. This issue is coming from the /src/App.js file

I've recently started diving into the routing section of learning react, but I'm a bit puzzled by the error message I encountered. Error: Failed to compile ./src/App.js 31:19-33 'react-router' does not contain an export named 'bro ...