Display loading icon in AngularJS during template retrieval

Imagine I have this specific directive:

angular
.module('app.widgets')
.directive('myCalendarRange', myCalendarRange);

function myCalendarRange () {
    var directive = {
      link: link,
      templateUrl: '/template/is/located/here.html',
      restrict: 'EA'
    };
    return directive;

    function link(scope, element, attrs) {
    /* */
    }
}

Is there a way to display a loading gif while Angular fetches the template?

UPDATE: I am also looking for a solution that can be applied to views. For instance, when a user navigates to the products page, I want to show the loading animation while angular retrieves the products.html

    $routeProvider
    .when('/Products', {
          templateUrl: 'products.html',
          controller: 'productsController',

    });

Answer №1

I just implemented it in this manner...

In the directive, include an HTML snippet with:

  1. Load code (and hide it once the template is loaded)
  2. Include the template (with an onload event, compatible with angular)
  3. Add a watch variable for loading in your scope

    angular
    .module('app.widgets')
    .directive('myCalendarRange', myCalendarRange);
    
    function myCalendarRange () {
        var directive = {
          link: link,
          /* Steps 1 and 2 */
          template: '<span ng-hide="loading == false">Loading... GIF</span><div ng-include="<url_template>" onload="loading = false"></div>',
          restrict: 'EA'
        };
        return directive;
    
        function link(scope, element, attrs) {
            scope.loading = true; //Step 3
        }
    }
    

By implementing this approach, you can display a template with a loading gif while loading the actual template (I have used this to show loading while the server generates a PayPal Form)

For example:

$routeProvider
.when('/Products', {
      templateUrl: 'loading.html', //General loading with Gif and include
      controller: 'productsController',

});

Loading.html

<div ng-hide="loading == false">
Loading please wait...<img src="ajax_loader_blue_64.gif" />
</div>
<div ng-include="url_template" onload="loading = false"></div>

ProductsController

//...
scope.url_template = 'URL to template to load set in the controller'
scope.loading = true
//...

Answer №2

Implement pace.js for a smooth loading experience. It's simple to use and truly impressive.

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

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

What is the method for modifying the input element within a TextField component from MUI?

I have TextField elements in my application that appear to be too large. Upon inspection, I noticed that the input element within them has default padding that is too big.https://i.stack.imgur.com/C13hj.png My query is regarding how to adjust the styling ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

Converting RGB color values to HSL color values using a unique, randomized Javascript approach

On this site, I have added a random color overlay to the media-boxes. Check it out here Thanks to the helpful folks at stackoverflow, I was able to create this script: var getRandomInRange = function(min, max) { return Math.floor(Math.random() * (ma ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

VueJs Axios - Managing Request Headers

Edit: Is it possible that this is a CORS issue, considering I am on localhost... When using Javascript, I have the ability to define request headers and handle responses like this: $(function() { var params = { // Request parameters } ...

Utilize AJAX to parse an HTML Table retrieved from an ASP page and extract targeted cell data

Within our work intranet, there exists an ASP page that retrieves data from a variety of sensors. This data is organized in a table format with multiple rows and columns. It struck me as interesting to showcase some of these outputs on our department&apos ...

Saving information using Socket.io server during the 'connect' event

Currently, I am working with socket.io along with MongoDB and promises. My goal is to save some data in Mongo when the session is established so that further socket events cannot be properly handled until this data is successfully saved. // Below is my si ...

What is the best way to send an object key/value pair to a Vue template?

I've made progress on my component, but I'm facing an issue where the links are going to http://localhost:5173/[object%20Object]. It seems like I've reached a mental roadblock. This is what my component looks like: <template lang="p ...

Can you explain the significance of the v-on="..." syntax in VueJS?

While browsing, I stumbled upon a Vuetify example showcasing the v-dialog component. The example includes a scoped slot called activator, defined like this: <template v-slot:activator="{ on }"> <v-btn color="red lighten-2" ...

Sending a parameter to a request-promise function within an iteration through a forEach loop

I have successfully implemented an API call for price data. However, I am facing an issue while trying to pass the variable exchange_pair_id into the then() function. Within the forEach loop, the exchange_pair_id is accurate for each asset. But inside the ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

the slider HTML control is missing a value

Exploring the Range Input Type in HTML When adjusting the value on a slider (Range input type), that value is displayed in a textbox. However, making the same adjustment in the textbox does not update the slider's value. Below is the code snippet: & ...

Maintaining the functionality of an AJAX web page even after extended periods of inactivity

When using my one-page web app, I sometimes leave the page open overnight and find that when I come back in the morning, things don't work as they should. It seems like Javascript is acting up - edit-in-place loads incorrect data, ajax calls fail to f ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

Arrange individuals using AngularJS into an alphabetical directory and apply filtering

Within my AngularJS application, I have an object where keys represent letters of the alphabet and each key contains an array of people. <div ng-repeat="(letter, group) in people"></div> <div ng-repeat="people in letter"></div> ...

Develop an array in JavaScript using PHP on the server side

I have successfully created a JavaScript array in PHP and sent it to the client. However, I am now wondering how to create a JavaScript array with PHP and store it on the server. Can anyone provide some guidance on this? Thanks in advance! ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

Click the mouse to create a unique path from the list items within the <ul> <li> using jQuery

My current listing contains various files and folders: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fon ...