A mask layer for each $http request in the Angualrjs Directive_angularjs

Source: Internet
Author: User

Angularjs is a very powerful front-end MVC framework. Using $http in Angualrjs to send a request to the remote API each time, waiting for a response, there is a bit of a wait process in between. How do you handle this waiting process gracefully?

If we pop a mask layer during the wait process, it would be a more elegant approach.

This involves intercepting the request response to the $http. When requested, a mask layer pops up and hides the mask layer when the response is received.

In fact, $httpProvider has provided us with a $httpprovider.interceptors property, we just need to put the custom interceptor into the collection.

How do you behave? This is roughly the case:

<div data-my-overlay>
<br/> Loading

Displays the loaded picture is contained in the directive, will certainly use transclusion.

Also involves a mask layer pop-up delay time problem, which we want to use in config through the API settings, so we need to create a provider, through this set delay time.

$http request responds to the directive of the mask layer:

(function () {var myoverlaydirective =function ($q, $timeout, $window, Httpinterceptor, Myoverlayconfig) {return {Restric T: ' EA ', transclude:true, scope: {myoverlaydelay: "@"}, Template: ' <div id= ' overlay-container ' class= ' Onverlaycontai Ner "> ' + ' <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 (); Initialize function init () {wireuphttpinterceptor (); if (window.jquery) wirejqueryinterceptor (); Overlaycontainer =
document.getElementById (' Overlay-container '); }//Custom angular HTTP Interceptor function Wireuphttpinterceptor () {//request blocking httpinterceptor.request = function (config) {// Determines if the condition of the display mask is met if (Shouldshowoverlay (Config.method, Config.url)) {ProcessRequest ();} return Config | |
$q. When (config);
}; Response Blocking Httpinterceptor.response = function (response) {processresponse (); return response | | $q. When (response);}//Exception blocking H
Ttpinterceptor.responseerror = function (rejection) {processresponse (); return $q. Reject (rejection);} Custom jquery http Interceptor function Wirejqueryinterceptor () {$ (document). Ajaxstart (function () {ProcessRequest ();}); $ (
Document). Ajaxcomplete (function () {processresponse ();});
$ (document). Ajaxerror (function () {processresponse ();}); //Processing Request function ProcessRequest () {Queue.push ({}); if (queue.length = 1) {timepromise = $timeout (function () {if (queue.le
Ngth) Showoverlay (); }, Scope.myoverlaydelay?
Scope.myOverlayDelay:overlayConfig.delay); }//Process response function ProcessResponse () {queue.pop (); if (queue.length = 0) {timerpromisehide = $timeout (function () {Hideove
Rlay ();
if (timerpromisehide) $timeout. Cancel (timerpromisehide); },scope.myoverlaydelay?
Scope.myOverlayDelay:overlayConfig.delay);
}//Show matte layer 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 '; The function Hideoverlay () {if (timepromise) $timeout. Cancel (timerpromise); overlayContainer.style.display = ' none ';}// Get the execution result of a function var getComputedStyle = function () {var func = null; if (Document.defaultview && document.defaultview.g Etcomputedstyle) {func = Document.defaultView.getComputedStyle} else if (typeof (DocUment.body.currentStyle)!== "undefined") {func = function (element, anything) {return element["Currentstyle"];} function (element, style) {reutrn func (element, null) [style];}}
(); Determines whether to display mask layer function Shouldshowoverlay (method, url) {var Searchcriteria = {method:method, url:url}; return Angular.isu
Ndefined (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;//launch Cycle}}) return retVal;
}
}
}
};
Configure $httpprovider var httpprovider = function ($httpProvider) {$httpProvider. Interceptors.push (' Httpinterceptor ');
Custom Interceptor var httpinterceptor = function () {return {};}; Provide configuration var myoverlayconfig = function () {//default configuration var config = {delay:500, excepturl: []};//set delay This.setdelay = Functio N (delaytime) {config.delay = delaytime}//Set exception handling URL This.setexceptionurl = function (urllist) {config.exceptURL = urllist;
};
Get configuration 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 the global configuration:

(Functioin () {
angular.module (' Customersapp '), [' Ngroute ', ' My. Directive '])
. config ([' $routeProvider, ' Myoverlayconfigprovider ', Funciton ($routeProvider, Myoverlayconfigprovider) {
...
Myoverlayconfigprovider.setdealy (m);
Myoverlayconfigprovider.setexceptionurl ({method
: ' Get ',
URL: '
} ';
}]);
());

The above is a small set to share the ANGUALRJS in each $http request when a mask layer directive, I hope to help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.