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>
Consider the following points related to this loading directive -
- Directive name is loading.
- It is restricted to Elements only.
- Three values can be passed by using three different attributes like showme, showerror, errormessage.
Now, use this directive as shown below.
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();
- }]);
Here, Controller's method "getData" is trying to make "$http.get" service call. Value for "controller.isLoading" has been assigned to true before making service call. It will be assigned to false in case of success or failure from service.
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>
Here, loading directive has been used as an element. And, three different values have been passed into the attribute of loading directive.
Find the attached zip file of project for the complete source code.
Conclusion
AngularJS directives are very powerful and important features. Developers can create new html components in the form of element, attribute, comments, etc.