Introduction
Directive is a very powerful feature of AngularJS. Directives are HTML remarks for an HTML DOM element, like an attribute (Restrict -A), Element name (Restrict -E), Comment(Restrict -C). It tells the HTML compiler of AngularJS to perform a specific behavior to that DOM element or even transform the DOM element and its children.
I will create one loader component by using directive.
Shown below is the code of AngularJS loader, by using directive.
- var app = angular.module("myapp");
- app.directive('loading', function () {
- return {
- restrict: 'E',
- replace: true,
- scope: {
- showme: '=',
- showerror: '=',
- errormessage: '='
- },
- templateUrl: 'components/loading.html',
- }
- })
loading.html code
- <div class="container">
- <div ng-if="showme" class="showme-loader">
- <img ng-src="ajax-loader.gif" width="20" height="20" />
- Please wait...
- </div>
- <div ng-if="showerror">
- <h4>{{errormessage}}</h4>
- </div>
- </div>
- Directive name is loading.
- It is restricted to Elements only.
- Three values can be passed by using three different attributes like showme, showerror, errormessage.
Controller -
- var app = angular.module("myapp");
- app.controller('homeController', ['$scope', '$http', '$q', function ($scope, $http, $q) {
- var controller = this;
- controller.title = "Loader Directive Example.";
- controller.isLoading = false;
- controller.errorMessage = "";
- controller.getData = function () {
- controller.isLoading = true;
- var deferred = $q.defer();
- $http.get('https://abcd').success(function (data) {
- deferred.resolve(data);
- controller.isLoading = false;
- }).error(function (err) {
- controller.isLoading = false;
- controller.errorMessage = "OOPS! Error While Fetching Data from Server.";
- console.log('Error retrieving data');
- deferred.reject(err);
- });
- return deferred.promise;
- }
- controller.getData();
- }]);
It will set "errorMessage" in case of failure of service.
Now, I will use this code in HTML file.
- <div>
- <h1>{{homeController.title}}</h1>
- </div>
- <div>
- <loading showme="homeController.isLoading" showerror="true" errormessage="homeController.errorMessage"></loading>
- </div>
Find the attached zip file of project for the complete source code.

Join the conversation! Your thoughts help the community grow.