The loading spinner feature in the UI Route does not function properly unless the $timeout component is included

In my Angular application that uses UI Router, I have set up subscriptions to the $stateChangeStart and $stateChangeSuccess events. Within these event handlers, I am toggling a controller property called "isLoading" to show or hide a loading indicator outside of the ui-view tag using an ng-show directive. Despite confirming through debugging that the events are firing and variables are being updated in JavaScript, the DOM does not reflect these changes between the start and success events, resulting in the loading indicator never showing up. To overcome this issue, I resorted to adding a $timeout with a delay of 0 seconds to ensure that the loading indicator appears.

$rootScope.$on("$stateChangeStart", function() {
    ctrl.isLoading = true;
});
$rootScope.$on("$stateChangeSuccess", function(ev, to, toParams, from, fromParams) {
    $timeout(function() {
      ctrl.isLoading = false;
    }, 0);
});

This JSFiddle http://jsfiddle.net/uwhetx7q/2/ illustrates the challenge I encountered.

By introducing the $timeout even with a minimal delay, the loading indicator briefly appears. However, without it, the variable update does not seem to take effect as expected.

I attempted manual calls to $apply and $digest functions but encountered errors indicating that these methods were already in progress.

I remain optimistic that there is a straightforward solution I might be overlooking to display my loading indicator correctly, as relying on an empty $timeout is not ideal :)

Thank you for any insight!

Answer №1

It seems like you are facing a scope/digest-timing issue. Your ctrl.isLoading variable is being set, but the spinner does not detect this right away. It will only update after the current digest cycle.

To solve this issue, follow these steps:

$rootScope.$on("$stateChangeSuccess", function(ev, to, toParams, from, fromParams) {
    $timeout(function() {
      ctrl.isLoading = false;
    });
});

Using $timeout without specifying a time will ensure that it runs after the current digest cycle has completed.

For more insights on scope/digest/apply, check out: http://www.example.com/angular-js-apply-timeout-digest-evalasync/

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 submission of a Vue form is unsuccessful when it contains a hidden field

When users login to my application, they first enter their email address like in Google Account login. Depending on the scenario, they are then redirected to a Single Sign-On (SSO) or shown a password field. In the Chromium documentation, this process is ...

JavaScript Code for Executing Function on Checkbox Checked/Unchecked

My goal is to display an image when the checkbox is checked and show text when it is unchecked. However, I am facing an issue where the text does not appear when I uncheck the checkbox. <input type="checkbox" id="checkword" onchang ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

Form submission using AJAX is failing to send the data correctly

I've been struggling with this particular piece of code for days now, and any assistance would be greatly appreciated. The issue I'm facing is that the script successfully calls the PHP file upon hitting the submit key, but it fails to post the ...

What is the most effective method to extract an ID from a URL that is written in various formats?

Does anyone know of a reliable method to extract an ID from various URL formats using javascript or jquery? https://plus.google.com/115025207826515678661/posts https://plus.google.com/115025207826515678661/ https://plus.google.com/115025207826515678661 ht ...

Trouble with displaying PHP and AJAX call after switching from JS fetch

Initially, I had a JavaScript function set up to retrieve Wikipedia articles for the chosen country. The code was originally sourced from JS Fiddle and it worked flawlessly. However, I have now been informed that my course mandates all API calls to be made ...

Exploring ways to retrieve nested values from JSON data using the Instagram API and Javascript

Trying to modify the script found at https://github.com/bigflannel/bigflannel-Instafeed in order to access Instagram photos on a website. Unfortunately, the script does not currently support displaying photo comments. I attempted to make modifications that ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Ensuring secure communication with PHP web service functions using Ajax jQuery, implementing authentication measures

jQuery.ajax({ type: "POST", url: 'your_custom_address.php', dataType: 'json', data: {functionname: 'subtract', arguments: [3, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { ...

What is the correct way to declare and use the useState hook in React?

I am currently working with TypeScript interfaces and the useState hook, attempting to properly type them. However, I encountered an error when comparing a prop variable with a useState variable. The error message states that This comparison appears to be ...

Creating a fresh object from a previous one using JavaScript:

I am working towards a goal where I aim to take an object with string values, translate those values, and then create a new object filled with the translated strings. For example, if I start with: const strings = { "name": "my name", "age": "my ag ...

Tips for bringing in an npm package in JavaScript stimulus

Looking to utilize the imageToZ64() function within the zpl-image module. After installing it with: npm install zpl-image I attempted importing it using: import './../../../node_modules/zpl-image'; However, when trying to use the function like ...

Step-by-step guide on building a personalized rxjs operator using destructured parameters

I am in the process of developing a unique RxJS filter operator that requires a destructured array as a parameter. Unfortunately, TypeScript seems to be throwing an error related to the type declaration: Error TS2493: Tuple type '[]' with a len ...

What are the steps to execute a module designed for NodeJS v6 LTS ES2015 in Meteor 1.4.x?

While I understand that Meteor includes NodeJS as a dependency, I'm facing an issue with a module written in ES6 that has a default argument value set within one of the Class methods. The problem arises when using Meteor v1.4.3.2: (STDERR) packages/m ...

Flowtype: Utilizing type hints for class-based higher order component

I am currently working on typehinting a higher-order component (HOC) that adds a specific prop to a passed Component. The code snippet looks like this: // @flow import React, { Component } from 'react'; import type { ComponentType } from 'r ...

Encountering an issue during the installation of the live-server package through npm. Despite running `npm audit`, the error still persists and remains

I'm a beginner in the world of JavaScript and I've been following a tutorial here to learn more. I'm currently trying to install the live-server package using npm, but I keep encountering the following error message. $ npm install -g live-se ...

NextJs getStaticPaths function is failing to render the correct page, resulting in a 404 error message being displayed

Hey there, I'm in a bit of a pickle as I've never used 'getStaticPaths' before and it's crucial for my current project! I followed the example code from NextJs's documentation on 'getStaticPaths', but when I try to ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

Is there a way to prevent ng-template-loader from scanning image src's?

Currently, I am beginning to incorporate webpack into my development workflow for an angular project. To create my templateCache, I have had to include the ng-template-loader. Below is a snippet of my webpack configuration: { test: /\.html$/, loa ...