A mask layer Directive_AngularJS for each $http request in AngularJS
AngularJS is a very powerful front-end MVC framework. Use $http in AngualrJS to send a request to the remote API each time and wait for the response. There is a slight waiting process in between. How to handle this waiting process gracefully?
It would be a more elegant approach if we pop up a mask layer while waiting.
This involves intercepting $http request responses. When requesting, a mask layer pops up, and when the response is received, the mask layer is hidden.
In fact, $httpProvider has already provided us with a $httpProvider.interceptors property, and we only need to put the custom interceptors into this collection.
How to behave? It’s roughly like this:
<div data-my-overlay> <br/><img src="spinner.gif" /> Loading </div>
Show that the loaded image is included in the Directive, and transclusion will definitely be used.
It also involves the issue of the mask layer pop-up delay time. We hope to set this through the API in the config, so it is necessary for us to create a provider and set the delay time through this.
$http request response mask layer Directive:
(function(){ var myOverlayDirective =function($q, $timeout, $window, httpInterceptor, myOverlayConfig){ return { restrict: 'EA', transclude: true, scope: { myOverlayDelay: "@" }, template: '<div id="overlay-container" class="onverlayContainer">' + '<div id="overlay-background" class="onverlayBackground"></div>' + '<div id="onverlay-content" class="onverlayContent" data-ng-transclude>' + '</div>' + '</div>', link: function(scope, element, attrs){ var overlayContainer = null, timePromise = null, timerPromiseHide = null, inSession = false, queue = [], overlayConfig = myOverlayConfig.getConfig(); init(); //初始化 function init(){ wireUpHttpInterceptor(); if(window.jQuery) wirejQueryInterceptor(); overlayContainer = document.getElementById('overlay-container'); } //自定义Angular的http拦截器 function wireUpHttpInterceptor(){ //请求拦截 httpInterceptor.request = function(config){ //判断是否满足显示遮罩的条件 if(shouldShowOverlay(config.method, config.url)){ processRequest(); } return config || $q.when(config); }; //响应拦截 httpInterceptor.response = function(response){ processResponse(); return response || $q.when(response); } //异常拦截 httpInterceptor.responseError = function(rejection){ processResponse(); return $q.reject(rejection); } } //自定义jQuery的http拦截器 function wirejQueryInterceptor(){ $(document).ajaxStart(function(){ processRequest(); }); $(document).ajaxComplete(function(){ processResponse(); }); $(document).ajaxError(function(){ processResponse(); }); } //处理请求 function processRequest(){ queue.push({}); if(queue.length == 1){ timePromise = $timeout(function(){ if(queue.length) showOverlay(); }, scope.myOverlayDelay ? scope.myOverlayDelay : overlayConfig.delay); } } //处理响应 function processResponse(){ queue.pop(); if(queue.length == 0){ timerPromiseHide = $timeout(function(){ hideOverlay(); if(timerPromiseHide) $timeout.cancel(timerPromiseHide); },scope.myOverlayDelay ? scope.myOverlayDelay : overlayConfig.delay); } } //显示遮罩层 function showOverlay(){ var w = 0; var h = 0; if(!$window.innerWidth){ if(!(document.documentElement.clientWidth == 0)){ w = document.documentElement.clientWidth; h = document.documentElement.clientHeight; } else { w = document.body.clientWidth; h = document.body. clientHeight; } }else{ w = $window.innerWidth; h = $window.innerHeight; } var content = docuemnt.getElementById('overlay-content'); var contetWidth = parseInt(getComputedStyle(content, 'width').replace('px','')); var contentHeight = parseInt(getComputedStyle(content, 'height').replace('px','')); content.style.top = h / 2 - contentHeight / 2 + 'px'; content.style.left = w / 2 - contentWidth / 2 + 'px'; overlayContainer.style.display = 'block'; } function hideOverlay(){ if(timePromise) $timeout.cancel(timerPromise); overlayContainer.style.display = 'none'; } //得到一个函数的执行结果 var getComputedStyle = function(){ var func = null; if(document.defaultView && document.defaultView.getComputedStyle){ func = document.defaultView.getComputedStyle; } else if(typeof(document.body.currentStyle) !== "undefined"){ func = function(element, anything){ return element["currentStyle"]; } } return function(element, style){ reutrn func(element, null)[style]; } }(); //决定是否显示遮罩层 function shouldShowOverlay(method, url){ var searchCriteria = { method: method, url: url }; return angular.isUndefined(findUrl(overlayConfig.exceptUrls, searchCriteria)); } function findUrl(urlList, searchCriteria){ var retVal = undefined; angular.forEach(urlList, function(url){ if(angular.equals(url, searchCriteria)){ retVal = true; return false;//推出循环 } }) return retVal; } } } }; //配置$httpProvider var httpProvider = function($httpProvider){ $httpProvider.interceptors.push('httpInterceptor'); }; //自定义interceptor var httpInterceptor = function(){ return {}; }; //提供配置 var myOverlayConfig = function(){ //默认配置 var config = { delay: 500, exceptUrl: [] }; //设置延迟 this.setDelay = function(delayTime){ config.delay = delayTime; } //设置异常处理url this.setExceptionUrl = function(urlList){ config.exceptUrl = urlList; }; //获取配置 this.$get = function(){ return { getDelayTime: getDelayTime, getExceptUrls: getExceptUrls, getConfig: getConfig } function getDelayTime(){ return config.delay; } function getExeptUrls(){ return config.exceptUrls; } function getConfig(){ return config; } }; }; var myDirectiveApp = angular.module('my.Directive',[]); myDirectiveApp.provider('myOverlayConfig', myOverlayConfig); myDirectiveApp.factory('httpInterceptor', httpInterceptor); myDirectiveApp.config('$httpProvider', httpProvider); myDirectiveApp.directive('myOverlay', ['$q', '$timeout', '$window', 'httpInceptor', 'myOverlayConfig', myOverlayDirective]); }());
In global configuration:
(functioin(){ angular.module('customersApp',['ngRoute', 'my.Directive']) .config(['$routeProvider, 'myOverlayConfigProvider', funciton($routeProvider, myOverlayConfigProvider){ ... myOverlayConfigProvider.setDealy(100); myOverlayConfigProvider.setExceptionUrl({ method: 'GET', url: '' }); }]); }());
The above is a mask layer Directive for each $http request in AngualrJS that the editor shared with you. I hope it will be helpful to everyone.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

This article outlines ten simple steps to significantly boost your script's performance. These techniques are straightforward and applicable to all skill levels. Stay Updated: Utilize a package manager like NPM with a bundler such as Vite to ensure

Sequelize is a promise-based Node.js ORM. It can be used with PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. In this tutorial, we will be implementing authentication for users of a web app. And we will use Passport, the popular authentication middlew

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...
