Creating a loading mask for a section of a webpage using angularjs

How can I implement a loading mask/image for a $http request that loads data for a <select> tag on my webpage? I want the loading mask/image to only cover the specific section of the page where the data is being loaded.

Here's the HTML code:

<select ng-model='widgetType' ng-options="widget.name for widget in allWidgets track by widget.id">
<fieldset id="needs-loading-mask" ng-disabled="widgetType.id">
  <div z-index=100 ng-if="loadingVariants"><img src="img/loading.gif" /></div>
  <select ng-model='widgetVariant' ng-optoins="variant.name for variant in allVariants track by variant.id>
<fieldset>

And here's the JavaScript code:

    $scope.$watch('widgetType.id', function(newValue, oldValue) {
        if(newValue) {
            $scope.loadingVariants = true;
            console.log("Getting variants from server");
            $timeout(function() { // for debug purposes
                $http.get('/api/widget-variants/?widget=' + newValue)
                    .success(function (data) {
                        $scope.allVariants = data;
                        $scope.loadingvariants = false;
                    }).error(function (data) {
                        $scope.loadingvariants = false;
                    });
                }, 1000);
        } else {
            $scope.allVariants = [];
        }
    });

I'm trying to figure out how to overlay a loading mask over #needs-loading-mask while $scope.loadingVariants is true. I need it to appear above the select dropdown element inside the parent fieldset using declarative syntax.

Removing the select element isn't an option as it affects tab order. Is there a way to position something in front of it without disrupting functionality?

Answer №1

$http is equipped to handle its tasks proficiently

An effortless approach, requiring only one boolean for management:

To create a service, use the following code snippet:

angular.module('services.httpRequestTracker', [])
    .factory('httpRequestTracker', ['$http', function ($http) {

        var httpRequestTracker = {};
        httpRequestTracker.hasPendingRequests = function () {
            return $http.pendingRequests.length > 0;
        };

        return httpRequestTracker;
    }]);

In the main controller (typically the app controller):

$scope.hasPendingRequests = function () {
   return httpRequestTracker.hasPendingRequests();
};

You can then add the following code anywhere on your page:

<div z-index=100 ng-show="hasPendingRequests()><img src="img/loading.gif" /></div>

The key element here is the

http.pendingRequests.length method
.

Answer №2

Tracking Requests with AngularJS

angular.module('services.requestTracker', [])
.service('requestTracker', ['$http', function ($http) {
    var requestTracker = {};
    requestTracker.hasPendingRequests = function () {
        return $http.pendingRequests.length > 0;
    };

    return requestTracker;
}]);

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 fixing alignment problems using CSS

I am experiencing a problem where I am unable to figure out how to align the content in one column with text positioned next to it in a right-aligned format. /* Personal Details */ .personal-info { width: 90%; padding: 25px; border-bottom: 1px so ...

What causes the disparity in functionality between CSS's Left 75% and Right 25% properties?

Here is my CSS code snippet: .bloodparam > .highvalue { bottom: 12px; right: 25%; } and .bloodparam > .highvalue { bottom: 12px; left: 75%; } I expected the element to be in the same position with both lines of code, but I'm noticing differe ...

Extract CSS from Chrome developer tools and convert it into a JavaScript object

Recently, we have started incorporating styles into our React components using the makeStyles hook from Material-UI. Instead of traditional CSS, we are now using JavaScript objects to define styles. An example of this is shown below: const useStyles = ma ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

Retrieving an Angular Application directly from the Server

In order to ensure user authentication from the backend before any other code loads in my Angular app, I need the initial request sent to the backend to check if the user is authenticated. Only once the user has been verified as authenticated can the app b ...

Strategies for efficiently parsing JSON in HTML using AngularJS

I have received this JSON format and I am looking to extract the message and username fields. How can I achieve this? Also, I want to format the date in Y-m-d format. I tried using ng-repeat but couldn't print the data. Can someone please help me disp ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

Discovering the CSS code for customization

As a beginner, I apologize in advance for any silly questions ˆˆ I am currently working on a website using bootstrap. Everything is functioning correctly, but I am struggling to override some CSS styles. In the image provided, you can see how I used the ...

"Reduce the height and adjust the row spacing of the Vuetify form for a more

I'm currently working on creating a form using vuetify that closely resembles the one shown in this image: After experimenting with vuetify grid and columns, I've managed to achieve something similar to this: My goal now is to reduce the height ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

What is the best way to increase the top padding of an anchor link?

I need to create a padding-top effect for my div when the link to the anchor is clicked: <a href="#myAnchor">Proceed to my anchor</a> ... <div id="myAnchor"> ... </div> The challenge lies in wanting to add the padding only when ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Solar Flare Malfunction

angular.module('starter') .controller('LoginCtrl', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) { $scope.loginForm = {} $scope.loginError = false; $scope.loginErrorText; ...

What is the code to create a forward slash on a webpage using HTML/CSS?

I want to create a unique parallelogram/slash design on my website. While it's simple to place two rectangles side by side, achieving the slash effect is proving to be quite challenging. Can this be done using only CSS or HTML, or does it require SVGs ...

Efficiently search and filter items across multiple tabs using a single search bar in the Ionic 2

I am currently working on implementing a single search bar that can filter lists in 2 different tabs within Ionic 2. The search bar is functional, and I have a method for filtering through objects. However, my goal is to allow users to select different tab ...

Struggling to properly bind data to this variable in AngularJs

Two Key Points to Note: 1. I am aiming to steer clear of using $scope as it may hinder the new "controller as" syntax. 2. It appears that my issue could be related to variable scope, so clarifying the correct JS approach might resolve the problem. Disrega ...

What is the best way to position the label above the input text in a Material UI TextField component with a Start Adornment?

Struggling to figure out the right Material UI CSS class to style a reusable TextField component? You're not alone. Despite tinkering with InputLabelProps (specifically the shrink class), I can't seem to get it right. Here's the code snippet ...

Tips on eliminating borders in react-table components

Within my React.js component, I have implemented a table using react-table along with some material-ui components displayed alongside the table: import React from 'react' import { useTable, useGlobalFilter, usePagination } from 'react-table& ...

Variability of pixel dimensions on various devices

When it comes to front-end design in CSS, the use of pixels as a measurement is quite common. However, with varying display sizes and resolutions, one might wonder how relevant this fixed pixel size really is. Is there a way to utilize real-world measure ...

Utilizing ngClassEven and ngClassOdd in Angular 2 for Improved Styling

I attempted to replicate the behavior of ng-class-even and ng-class-odd (originally from Angular 1) in my Angular 2 application. Below is the code I wrote and it's functioning correctly, but I'm curious if there are alternative methods to achiev ...