Loading spinner in AngularJS for displaying during DOM rendering

I have a page with 8 tabs, each containing a lot of HTML controllers (data bindings), resulting in slow data rendering.

To address this issue, I implemented an ng-if condition based on the active tab determined by ng-click. The active tab is visually indicated using a CSS class. After implementing the ng-if condition, the default tab loads quickly and subsequent tab clicks trigger loading for each tab. However, each tab takes approximately 3 to 6 seconds to render, leaving the user unaware of the loading process. To improve user experience, I am considering adding a loading spinner.

My objective now is to display an AngularJS loading spinner when clicking on each tab until the tab is completely rendered (the tab remains inactive until ng-repeat finishes rendering). The plan is to show the spinner during the ng-click event and remove it once ng-repeat completes rendering. However, I encountered an issue with the timing of the spinner initiation. Even though I trigger the spinner logic in ng-click, it starts towards the end of the tab rendering process and stops immediately as ng-repeat finishes. This happens due to background processes affecting the spinner's functionality. How can I effectively implement a loader or loading message for tab rendering? Below is my sample code for the page, ng-click event, and identifying the end event of ng-repeat:

HTML Code:

<div class="claimant-data-nav " ng-controller="MyController">
    <ul class="nav nav-tabs ">
        <li ng-repeat="tabname in Mylist | unique:'TabName'" ng-class="{'active':tabname.TabName == 'Tab1'}">
            <a data-target="#tab-{{tabname.TabName}}" data-toggle="tab" ng-click="activetab(tabname.TabName)">{{tabname.TabName}}</a>
        </li>
    </ul>
    <div class="tab-content">
       <a data-toggle="tab" class="mobile-tabs" data-target="#tab-{{tabname1.TabName}}" href="javascript:void(0)" ng-repeat="tabname1 in Mylist | unique:'TabName'">{{tabname1.TabName}}</a>
       <div id="tab-{{tabname2.TabName}}" ng-class="{'tab-pane fade active in':tabname2.TabName == 'Tab1','tab-pane fade':tabname2.TabName != 'Tab1'}" ng-repeat="tabname2 in Mylist | unique:'TabName'">
            <div ng-if="activetab == tabname2.TabName">
              <div ng-repeat="item in items" on-finish-render="ngRepeatFinished">
                  <!-- data binding logic here.It has lot of angularjs databindings.-->
              </div>

            </div>
        </div>
    </div>
</div>    

In the ng-click function, I initiate the loader:

.scope.activetab = function(tabname){
    showloader();
    //some other codes here to set active tab etc.
}

To determine the completion of ng-repeat, I utilized the following directive:

app.directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    }
});

$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
   removeLoader();
});

Answer №1

To activate the tab, consider utilizing the $timeout function in order to initiate the spinner and then wait for its promise to proceed with activating the designated tab:

.updateTab = function(tab){
    $timeout(function() {displayLoader();})
        .then(function() {
            //additional code to set the specified tab as active
        });
};

Answer №2

To show or hide content in your AngularJS application, you can utilize the ng-show directive. Here's an example to guide you:

Include a loader message in your HTML like this:

<div ng-show="load">Loading...</div>

In your controller:

app.controller("showCustomer", function ($scope,myService) { 
loadCustomers();
function loadCustomers() {
    $scope.load=true;
    var promiseGet = myService.loadCustomer();

    promiseGet.then(function (obj) {
        $scope.Customer = obj.data;
        $scope.load=false;
    },
          function (errorObj) {
              $scope.error = 'failure loading Customers', errorObj;
              $scope.load=false;
          });
}

For more information, you can also check out this link:

I hope this explanation proves useful for you.

Best regards.

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

Tips for preventing Uncaught SecurityError: Blocking a frame with origin in phonegap

I'm in the process of developing a phonegap application that serves as a miniature browser for a client's website. This app will allow the client's customers to access their favorite pages with ease. Once a user selects a favorite, it will b ...

Using PHP to generate tables in combination with pdfMake and AngularJS for creating

I am new to PHP and AngularJS. My webpage interacts with a web server using PHP - AJAX. It retrieves data from a database, displays it as a large table in an html placeholder. Now, I am looking to allow users to download the content of that table in a PD ...

Learn the process of effortlessly transferring user information to a MongoDB database

Using socket.io, I am broadcasting geolocation data (lat, lng) and updating the marker icon on a map every time a user connects to the app. When a user from Japan connects, their position is shared with me and vice versa. The issue arises when I only want ...

Instructions for transferring a JavaScript array to a Java servlet

Greetings everyone! I am currently working on a web application with an orthodox approach, utilizing AJAX in Java and JavaScript. I am wondering if it is feasible to pass an array from JavaScript to a Servlet. ...

Proto-Type Namespace

I have a class named "Animals" which serves as a namespace for other classes, "Crocodile" and "Monkey": var Monkey = function(Animals) { this.Animals = Animals; }; Monkey.prototype.feedMe = function() { this.Animals.feed(); }; var Crocodile = functi ...

Implementing file uploads in an Ionic application with a Web API

My dilemma is as follows: I am working with a WEB API where I need to upload images of boards. What do I need to do? Allow the user to select an image from their phone Enable the user to add a name for the board When the user clicks submit, the entered ...

Refining an array with React's filter method

Currently, I am in the process of creating a To-Do Application using React. However, I have encountered a roadblock along the way. My struggle lies in mapping through items within an array and presenting them in an unordered list. I am attempting to util ...

Utilizing Axios Instances for Authorization in Next.js Data Fetching

I am currently utilizing NextJS version 12.0.10 along with next-redux-wrapper version 7.0.5. I have implemented an Axios custom instance to store the user JWT token in local storage and automatically include it in every request, as well as to handle errors ...

What steps should I take to make index.html the default page on my http server?

I have set up an AngularJS application in a Node environment. I am using the http-server module to serve the files to the browser. Despite everything working smoothly, I'm struggling to make index.html the default file when the server launches. I hav ...

I'm attempting to switch between different "screens" by utilizing divs with CSS and JavaScript, using the display property to toggle between none and block. Everything seems to be functioning smoothly except for the

I thought I grasped the concept of this because all my toggles are working fine, except for the last one. The frustrating part is that it's written in the same manner as the others before it. The problematic button is identified by id="startYearOne". ...

Tips for creating a login/registration system in a single page application

I've been working on a single-page application with ngRoute for navigation between tabs. Now, I need to incorporate a login and registration feature. After that, users should be able to access all the tabs. I'm unsure about the following: 1) Sho ...

pictures in photo display

Please check out my codepen project: html code: <body> <div class="thumbnails"> <a href="#"><img src="http://s30.postimg.org/4yboplkxd/dotty.jpg" width="100" height="100"></a> <a href="#"><img src="http:// ...

PhantomJS reveals underlying jQuery bug

Currently, I am developing automated test scripts that require a headless browser (PhantomJS) to perform all DOM navigation and actions except for downloads. So, PhantomJS seems like the right choice. However, I am encountering errors when trying to use P ...

jQuery for Implementing Pagination Across Multiple Tables

As a novice in the world of JavaScript and jQuery, I am struggling with implementing pagination for multiple tables on a single page. My goal is to have several tables that can be paginated using one navigation system. However, all my attempts so far have ...

Printing documents from a database using Mongoose version 7.3.1: A comprehensive guide

Currently, with Mongoose 7.3.1, I have inserted some documents into the MongoDB database. However, when I try to log these documents using console.log() by using Fruit.find({}) and outputting it to the console, I get a massive dataset of unwanted objects. ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...

Implementing React.JS to dynamically update a value from a websocket and store it within

I want to create a dynamic stock price table that updates with live stock prices using websockets. I have all the necessary data and need to update my stock price object with the live price. How can I access the variable and insert the value into the obj ...

Does PHP/AJAX only function when an output is generated?

I am attempting to fetch the Wordpress blog header into a php file in order to use it for an AJAX call function. define('WP_USE_THEMES',false); echo 'Something'; require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-b ...

Finding all items in an array in Cypress and validating them using JavaScript assertions

After making an API call, I have received an array response that includes the following information: [ { "IsDatalakeEnabled": true, "RecoveryHr": { "IsRecoveryHREnabled": false, &quo ...

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...