Ajax Loader using Angularjs

Introduction
In this article i am focus on How to implement Ajax Loader or busy Indicator using AngularJs
Custom Directive for loader
Angular Directives are markers of a DOM element. Using this you can create your own custom elements,custom events.

More about angular directives

Here i am going to create a custom attribute directive named busyindicator to show a busy loading indicator during Ajax call.


(function () {
"use strict";
angular.module("App").directive("busyindicator", busyIndicator);
function busyIndicator() {
var directive = {
restrict: "A",
link: function ($scope) {
$scope.$on("showBusyIndicator", function () {
$scope.canShow = true;
});
return $scope.$on("hideBusyIndicator", function () {
$scope.canShow = false;
});
}
};
return directive;
}
})();

If any http request is in progress , Angular JS will automatically update the anyRequestInProgress property to true on the scope object and once the request complete it will set back to false. In this directive link function i have created a angular watch function whenever if any changes in anyRequestInProgress property it will notify this method.

Apply the busyindicator directive to the html element as an attribute also the visible status property canShow to angularjs ng-show directive to hide and show the div.

 

//CSS for showing loader image in the center of a screen

#loaderdiv
{
display : none;
}
#loaderdiv.loader {
display : block;
position : fixed;
z-index: 100;
background-image : ‘loader.gif’
-ms-opacity : 0.4;
opacity : 0.4;
background-repeat : no-repeat;
background-position : center;
left : 0;
bottom : 0;
right : 0;
top : 0;
}


You no need to write any code for show & hide loader element . Our custom directive automatically handle this based on our service request.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s