Scope wrapping causing AngularJS controller to not display data

My AngularJS setup is causing issues with setting up a function in a controller.

Here is the code snippet from the controller:

$scope.totalUnpaid = 0;
$scope.totalPaid = 0;
$scope.totalHalfDue = 0;
$scope.totalHourDue = 0;
$scope.totalBuisness = 0;
$scope.totalUnpaidSesh = [];
$scope.totalPaidSesh = [];

const getTheSessions = () => {
  adminService.getAllSessions().then((response) => {
    console.log(response);
    response.data.forEach(e => e.next_class = e.next_class.substring(0, 10));
    $scope.allSessions = response.data;

    for (var payment in $scope.allSessions) { 
      if ($scope.allSessions[payment].payment == 'Paid') { 
        $scope.totalPaid++; 
        $scope.totalPaidSesh.push($scope.trainerSesh[payment]);
      } else { 
        $scope.totalUnpaid++; 
        $scope.totalUnpaidSesh.push($scope.allSessions[payment]);
      }
    }

    for (var next_session in $scope.totalUnpaidSesh) {
      if ($scope.totalUnpaidSesh[next_session].next_session == '30_Minute') {
        $scope.totalHalfDue = $scope.totalHalfDue + 25;
      } else if ($scope.unpaidSesh[next_session].next_session == 'Hour_Session') {
        $scope.totalHourDue = $scope.totalHourDue + 50;
      }
    }

    $scope.totalBuisness = $scope.totalHalfDue + $scope.totalHourDue;

  });
};

I am facing an issue where the requested data doesn't show up in the controller even though it's present when I log it in the service.

Strangely enough, when I remove the `$scope` and directly access the service like this:

$scope.totalUnpaid = 0;
$scope.totalPaid = 0;
$scope.totalHalfDue = 0;
$scope.totalHourDue = 0;
$scope.totalBuisness = 0;
$scope.totalUnpaidSesh = [];
$scope.totalPaidSesh = [];


adminService.getAllSessions().then((response) => {

        console.log(response);
        response.data.forEach(e => e.next_class = e.next_class.substring(0, 10));
        $scope.allSessions = response.data;

        for (var payment in $scope.allSessions) { 
          if ($scope.allSessions[payment].payment == 'Paid') { 
            $scope.totalPaid++; 
            $scope.totalPaidSesh.push($scope.trainerSesh[payment]);
          } else { 
            $scope.totalUnpaid++; 
            $scope.totalUnpaidSesh.push($scope.allSessions[payment]);
          }
        }

        for (var next_session in $scope.totalUnpaidSesh) {
          if ($scope.totalUnpaidSesh[next_session].next_session == '30_Minute') {
            $scope.totalHalfDue = $scope.totalHalfDue + 25;
          } else if ($scope.unpaidSesh[next_session].next_session == 'Hour_Session') {
            $scope.totalHourDue = $scope.totalHourDue + 50;
          }
        }

        $scope.totalBuisness = $scope.totalHalfDue + $scope.totalHourDue;

  });

The data shows up as expected.

Why does it work without the method `getTheSessions`, but not when it is included?

Answer №1

One way to retrieve session data is by using the $ngInit life-cycle hook:

this.$ngInit = fetchSessionsData;

function fetchSessionsData() {
  adminService.getAllSessions().then((response) => {
    console.log(response);
    response.data.forEach(entry => entry.upcoming_session = entry.upcoming_session.substring(0, 10));
    $scope.allSessions = response.data;

    // Additional code here
  });
}

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

Using location.reload with the argument of true is no longer recommended

While it's generally not recommended to reload an Angular Single Page Application, there are situations where a full reload is necessary. I've been informed by TSLint that reloading is deprecated. Is there any other solution available for this ...

jQuery code unable to alter the class of a div

Need help with a script on my single page site that adds a "read more" style link to a content area's div. The goal is for the button to change the class of the content area when clicked, showing all of the content. Clicking again should hide the cont ...

AngularJS - Send selected items from a list

If a checkbox is selected and the submit button is clicked, I want to insert data into the database. <tbody> <tr ng-repeat="item in rows | filter:search"> <td>{{item.isbn}}</td> <td>{{item.book_title}}</td> ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

Matching list symbols in regular expressions (Angular 2)

I have been attempting to find a solution for matching a list of symbols using regex, but I keep encountering errors in the result. The symbol list includes: !@#$+*{}?<>&’”[]=%^ if (text.match('^[\[\]\!\"\#&bs ...

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

What are the steps to incorporate SlickGrid (or any jQuery plugin) into my website?

Looking at my site's folder structure, I see that all jQuery files are located in the js directory. However, upon examining the SlickGrid download, I noticed that it comes with its own version of jQuery. I would prefer to have just one copy of jQuery ...

Error in the code causing images to shift positions

My JavaScript code is encountering a strange glitch, and I'm not sure if it's related to my math calculations or the way my code is structured. The concept behind my project involves left-clicking and dragging to scroll through a map displayed o ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

Obtain the data from a nested array

I'm facing a situation where I have the following code: var obj = { level1 : { level2 : 'value' } }; I also have another object: var returnData = { value: "level1.level2", anotherThing: "level1" }; The goal is to ...

Is it possible to create an async hover provider in a VSCode extension?

Currently, I'm working on a vscode extension where I need to perform a database lookup using a string that the user hovers over as a key. I have implemented a hover provider as an async function, but unfortunately, it is not displaying when I hover ov ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

Angular directives that control the enclosing scope

I am facing a challenge with binding my directive to a model in the controller that encloses it. The ng-model value is not getting passed into the directive, causing the model to display as the variable name "val" once it's rendered. template: &apo ...

Place the retrieved data from the API directly into the editor

I've integrated the LineControl Editor into my app and everything is functioning perfectly, except for when I attempt to insert text into the editor. Here's the link to the LineControl GitHub page: https://github.com/suyati/line-control/wiki Fo ...

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Dynamic navigation menu with Bootstrap's responsive multi-level design

I recently developed a multi-level navigation menu using Bootstrap. Everything seems to be working smoothly when the screen size is 1200px or above. However, I encountered an issue with the second level dropdown menu not opening upon clicking on screens sm ...

"Enhanced file manager: Elfinder with multiple buttons to seamlessly update text input fields

Every button is responsible for updating the respective element: <input type="text" id="field" name="image" value="<?php echo @$DuzenleSonuc[0]['image']; ?>" /> I need to ensure that each button updates the correct field: onclick ...

What is the best way to check the difference between the current date and time with another date and

Seeking assistance in comparing 2 dates using JavaScript has been a bit challenging for me. I haven't found the exact solution on this platform yet. As a beginner in JavaScript, I initially assumed that obtaining the current date and time would be a s ...

Navigating Angular's ng-grid: Utilizing JSON attributes structured with continually increasing integers

Currently, I am facing an issue with populating an ng-grid instance using JSON received from a rest API. In the past, I successfully tested this setup and it was working without any configuration problems. The previous JSON response had a top-level "users" ...