Angular JS Directive is an extension of HTML tags.
It helps the developer to use custom tags and provides reusability.
We can define and implement custom tags and custom directive., which helps the user to use resuse the same template and logic all over the application reducing the overhead of writing everywhere.
Following are different ways of declaring custom tags and custom attributes.
Using the keyword “restrict”, type of directive can be defined.,
- C>– Directive used as class name in HTML element.
(Example: restrict=”C” …. <div class=”customdirective”/>) - A – Directive used as attribute in HTML element.
(Example: restrict=”A” …. <div customdirective>) - M– Directive can be used as comments in HTML.
(Example: restrict=”M” …. <!–Using directive:customdirective–>) - E – Directive used as element in HTML element.
(Example: restrict=”E” …. <customdirective></customdirective>)
Below example explains the “Element” directive widely used.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<!doctype html> <html> <head> </head> <body> <div ng-app="sampleApp" ng-controller="sampleController"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> <script> var sampleApp = angular.module("sampleApp", []); sampleApp.directive('user', function() { var customDirective = {}; customDirective.restrict = 'E'; customDirective.template = "The user <b>{{user.name}}</b> has a <b>{{user.role}}</b> role."; customDirective.scope = { user : "=name" } customDirective.compile = function(element, attributes) { element.css("border", "1px solid #cccccc"); var linkFunction = function($scope, element, attributes) { element.html("The user <b>"+$scope.user.name +"</b> has a "+$scope.user.role+" role in Organization..</b><br/>"); } return linkFunction; } return customDirective; }); sampleApp.controller('sampleController', function($scope) { $scope.user1={}; $scope.user1.name="Johny"; $scope.user1.role="developer"; }); </script> <user name="user1" /> </div> </body> </html> |
Output: