The $scope object in Angular is supposed to display the $scope.data, but for some reason, when I attempt to access it

Having an issue with my controller that fetches data from a service.

After receiving the data in the controller, I'm using $scope to pass it to the view.

Strange behavior - console.logs inside the 'then' function display the data correctly. However, outside of it, when I try to access $scope.data, it shows up as an empty object.

Could there be an error in my code?

(function() {

  angular
    .module("eplApp")
    .controller("tableCtrl", TableController);

  TableController.$inject = ['httpService', "$scope"];

  function TableController(service, $scope) {
    var apiTableUrl = "http://api.football-data.org/v1/soccerseasons/426/leagueTable";
    $scope.data = {};

    service.getListFromUrl(apiTableUrl).then(function(data) {
      $scope.data = data;
      console.log($scope);
      console.log($scope.data);
    });
    console.log($scope);
    console.log($scope.data);
  }
})();

Answer №1

Angular operates asynchronously, which is why attempting to log it outside of a service response will not work

To properly display the data, follow this example:

function DisplayController(service, $scope) {
  $scope.info = {};

  service.getDataFromEndpoint(apiInfo).then(function(responseData) {
    $scope.info = responseData;
    showData();
  });

  function showData() {
    console.log($scope.info);
  }
}

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

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript. I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation: HTML: <ul id="myL ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Include certain tags to the content within the text apart from using bbcode tags

I need help with a project involving a BBCODE editor that can switch between a WYSIWYG editor and a code editor. The visual editor is designed with a drag-and-drop block system for elements like pictures and text. In the visual editor, when a user drags ...

The $http.get request is successful only when the page is initially loaded for the first

Imagine this scenario: a user navigates to http://localhost:3000/all, and sees a list of all users displayed on the page. Everything looks good so far. However, upon refreshing the page, all content disappears and only raw JSON output from the server is sh ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encou ...

What is the best way to retrieve the values of "qty" and "price" and access them within the item [array] without knowing the IDs?

I am currently working on a shopping cart project, specifically on the "previous orders" page to display order details. My goal is to output this information in an (.ejs) file. The data structure includes nested objects, and within one object, propertie ...

Step-by-step guide on integrating async and await functionality into Vuetify rules using an ajax call

I'm currently using Vuetify form validation to validate an input field, and I'm exploring the possibility of making an ajax get call await so that I can utilize the result in a rule. However, my attempts at this approach have not been successful! ...

The functions that have been imported are not defined

I encountered a Error in created hook: "TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.$_playerApi_getPlayers is not a function" issue while using Webpack through Vue CLI on my webpage. Below is the structure of my project directory: . + main.js + ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Updating React props using useState?

Below is a component that aims to enable users to update the opening times of a store. The original opening times are passed as a prop, and state is created using these props for initial state. The goal is to use the new state for submitting changes, while ...

JQuery's .each method is executed prior to making an Ajax request

I am currently working on a JavaScript (jQuery) function that loops through input elements in a form, builds an array to convert into a JSON string, and then sends it to an AJAX endpoint. However, I am facing an issue where the loop runs after the AJAX cal ...

The functionality of the jQuery scroll feature appears to be malfunctioning

I am trying to implement a scroll event and have written the following code: <script type="text/javascript> $(function () { $(window).scroll(function () { alert($("body").scrollTop()); }); }); ...

Creating a JQuery slider that efficiently loads and displays groups of elements consecutively

Currently, I am in the process of developing an infinite horizontal tab slider using jQuery. My main objective is to optimize loading time by having the slider display only the first 10 slides upon initial page load. Subsequent slides will be loaded as the ...

React Navigation Bar Links Fail to Show Content

I'm a beginner in the world of React and I could really use some assistance. Right now, I am working on creating a portfolio using React and focusing on the Nav component. Although I haven't encountered any errors in the Console, when I click on ...