Introduction
Angular JS is great JavaScript framework for building client side application for the web since Angular code is developed using JavaScript. So that Angular has all of the issues that come with coding of JavaScript, no strong datatyping, global namespace issues and lack of class based object oriented techniques. Typescript solves these issues and make it easier to build, refactor and maintain your Angular JS application. If you want to improve development and refactoring activities, using Typescript is a great choice.
In this tip, I am going to focus on how to implement Ajax Loader or busy Indicator using AngularJs and Typescript.
You can see the Angular JS implementation from here.
Custom Directive for Loader
Angular Directives are markers of a DOM element. Using this, you can create your own custom elements, custom events.
Here, I am going to create a custom attribute directive named busyindicator
to show a busy loading indicator during Ajax call.
((): void=> {
"use strict";
angular.module("App").directive("busyindicator", busyIndicator);
function busyIndicator($http:ng.IHttpService): ng.IDirective {
var directive = <ng.IDirective>{
restrict: "A",
link(scope: App.Scope.IBusyIndicatorScope) {
scope.anyRequestInProgress = () => ($http.pendingRequests.length > 0);
scope.$watch(scope.anyRequestInProgress, x => {
if (x) {
scope.canShow = true;
} else {
scope.canShow = false;
}
});
}
};
return directive;
}
})();
module App.Scope {
export interface IBusyIndicatorScope extends angular.IScope {
anyRequestInProgress: any;
canShow: boolean;
}
}
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 is complete, it will set back to false
. In this directive link function, I have created an Angular watch function whenever there are 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
.
<div id="loaderdiv" ng-show="canShow" class="loader" busyindicator>
</div>
#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 do not need to write any code for show & hide loader element, custom directive will automatically handle this based on the service request.