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

Change the size of the image to use as a background

I have an image that is 2000x2000 pixels in size. I originally believed that more pixels equated to better quality with less loss. Now, I am looking to display it on my browser at a resolution of 500x500. To achieve this, I attempted to set the image as t ...

applying conditional rendering in vue.js

I'm currently working on developing a chat application using the guidelines outlined in this tutorial: https://socket.io/get-started/private-messaging-part-1/ One of my goals is to customize the appearance of the messages, so that when a message is s ...

Discovering the content within table cells by utilizing JavaScript functions linked to specific IDs

I am currently working on a project that involves a dropdown list: <select id="itemsList" onchange="gettingList()"> <option>Please choose an option</option> <option value="50">Shampoo</option ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

Snap to the top of the table with merged columns using scroll feature

I am currently attempting to create a table with horizontal scrolling and snapping behavior for the yellow header columns that span multiple columns. These headers should snap to the end of the red column, while always maintaining alignment at the beginnin ...

What is the best way to create fading text effects in an AngularJS application?

Running an AngularJS web application that showcases three words for 5 seconds each: Hello, World & Goodbye. The controller setup is as follows: self.currentIndex = 0; self.myTexts = ['Hello', 'World', 'Goodbye']; self.cu ...

Ensure that each row contains no more than 5 items, and use flexbox to automatically resize

I currently have the following setup: .container { background: gray; width: 600px; display: flex; flex-flow: row wrap; position: relative; } .item { background: blue; width: auto; height: auto; margin: 4px; flex: 1; flex-basis: 20% ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

Is using CSS as an HTML attribute considered poor practice?

I've been noticing an increasing trend of combining HTML, CSS, and JavaScript together in web development. However, I was taught to keep them separate with HTML linking to the sources/scripts. While using the style attribute in HTML is sometimes acce ...

How come the cubic bezier timing function works flawlessly just on the first try when staggered transitioning element opacity over time with CSS and a touch of JS?

I'm currently working on a menu overlay that expands to fill the screen when a user clicks a button in the corner. I'd like the menu items to fade in one by one, similar to the effect used on this website: Most of the functionality is there, but ...

Having various ng-apps within a single parent app

Exploring angularjs for the first time and experimenting with multiple ng-apps on a single page. For example, having app2 inside app1 and app1 within rootApp. controller1 includes an $http service that retrieves id and name values and assigns them to $roo ...

line of checkboxes aligned horizontally with the help of Bootstrap

My goal is to create a horizontal row of checkboxes within a form. I've been able to achieve a functional but unattractive version by using the following code: div.form-group(ng-show = 'avariable') label 1 input(type = 'checkbo ...

"When using Webpack and Sass, the background image specified with background: url() is processed correctly. However, when using webpack-dev-server, the image is

Currently, I am utilizing Webpack 2 in conjunction with webpack-dev-server and Sass loader. Here is my current configuration: { test: /\.scss/, loaders: [ "style", { loader: "css", query: { modules: false, sourceMap: true } }, ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Tips for converting data values within a kendo grid

I am attempting to translate data values in a kendo grid, but my current solution is not working as expected. Here is what I have tried: <div id="myDiv" kendo-grid k-data-source="controller.items" k-columns='[{ "field": "status", "title": "Stat ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Delaying Jquery on scroll Event

Hey there, I've got a set of icons that I'd like to reveal one by one as you scroll down. I've incorporated some animations from , but now I'm wondering how I can implement a delay function in my jQuery so the icons appear sequentially ...

Angular 2 has upgraded its Controller functionality by replacing it with Component

I find it a bit challenging to distinguish between Component and Controller. How was the Controller replaced by component in Angular 2? I came across this description of a component: In Angular, a Component is a distinct type of directive that utilizes a s ...

Issue with animation transition not triggering on initial click

I am currently working on creating an animation for a form using JS and CSS. Here is the code snippet I have: var userInput = document.getElementById("login-user"); var userLabel = document.getElementById("user-label"); // User Label Functions funct ...

Tips for setting height within a flexbox layout?

Is there a way to specify the height of rows in a flex wrap container so that text containers appear square on both smaller and larger screens? I want the sizing to be dynamic, adjusting as the window is resized. Check out this example on CodeSandbox Loo ...