Angular Custom Directives for Beginners


This article shows how to create a custom directive and use it in our project in angular js. This tutorial is for beginners/fresher or students. It also explains the use of directive operation in a single page coding. I hope it will be helpful for you to use of custom directive in your program. The directive is a small part of the DOM element we can use on our design page. HTML compiler uses directive and convert small elements in our page as a child. There are many pre-created directive elements in Angular js, such as ng-app, ng-controller, ng-init,ng-model, ng-bind, etc.

Angular Js Code Points

ng-app - This directive is used to bootstrap the application. Normally, it is put in a top-level element like HTML or body tag.
ng-controller - It is the main component of AngularJS which contains the state and logic both. It acts as a bridge between services and views.
$scope - Provides and link between the data and views. It holds all the required data for the views and used within the HTML template.
{{expression}} - This is called expressions and JavaScript-like code can be written inside. It should be used for mainly small operations in an HTML page.
ng-init -This directive provides us a way to initialize a variable on the page.
ng-repeat - It actually repeats the element on which it is used, based on the provided list of data.
Example Screenshot

Section 1

Section 1 shows a short view of the code part. We add an attribute ng-app myApp in HTML tag and in body part we add ng-controller myDirtveCtrl. Both ng-app and ng-controller is two main part of Angular js. Another in header tag we include angular.min.js and link bootstrap.min.css to run angular js functionality and design CSS. In HTML we add code to get an Angular app by using angular.module() function so we can access controller by using "appName".controller() function. 
  1. <!DOCTYPE html>    
  2. <html ng-app="myApp">    
  3. <head>    
  4.     <link href="bootstrap.min.css" rel="stylesheet" />    
  5.     <script src="angular.min.js"></script>    
  6.     <title>AngularJS Custom Directives</title>    
  7.     <style type="text/css">    
  8.     <!-- style in source code section-->        
  9.     </style>    
  10.     <script>    
  11.     // script code below or available in source code.    
  12.     </script>    
  13. </head>    
  14. <body ng-controller="myDirtveCtrl">     
  15. </body>    
  16. </html>    
Next, we create two custom directives named myCalcutator and interestCalculator to be used as a child element. Now, we are going to explain one directive interestCalculator. Use appName.directive() function to create custom directive in angularjs. It is very simple since first you create simple page for our directive code then run perfect as then use actual code in our program to create a directive. Also, if you have good experience in Angularjs coding, then you can create it in our program. To create a directive, use the three properties Restrict, Link and Template. In the restrict property. the  value is "AEC". This means we can use a custom directive as Attribute, Element and Class. The next one is link property, which can use to access custom directive function or variable. Here, we created function() with parameter $scope. Finally, the property template can be used to design our custom directive element.
  1. <script>  
  2.      var myApp = angular.module('myApp', []);  
  3.      // create directive  
  4.     myApp.directive('myCalcutator',function(){  
  5.             return {  
  6.                 restrict: 'AE',  
  7.                 link:function($scope){  
  9.                     $scope.ActAdd = function (calcu) {  
  10.                         calcu.res = Number(calcu.num1) + Number(calcu.num2);  
  11.                         calcu.act="+";  
  12.                     }  
  13.                     $scope.ActSubtract = function (calcu) {  
  14.                         calcu.res = calcu.num1 - calcu.num2;  
  15.                         calcu.act="-";  
  16.                     }  
  17.                     $scope.ActMultiply = function (calcu) {  
  18.                         calcu.res = calcu.num1 * calcu.num2;  
  19.                         calcu.act="x";  
  20.                     }  
  21.                     $scope.ActDivide = function (calcu) {  
  22.                         calcu.res = calcu.num1 / calcu.num2;  
  23.                         calcu.act="/";  
  24.                         if(isNaN(calcu.res))calcu.res=0;  
  25.                     }  
  26.                     $scope.ActClear = function (calcu) {  
  27.                         calcu.num1=0;calcu.num2=0;calcu.res=0;   
  28.                         calcu.act="";                             
  29.                     }  
  30.                 },  
  31.                 template:  
  32.                     '<div class="container" style="width:300px;" ng-init="calcu={num1:0, num2:0,res:0}">' +  
  33.                     '<div id="calcone" class="row">' +  
  34.                     '<h2>Simple Calulator</h2>' +  
  35.                     '<table table table-condensed >' +  
  36.                     '<tr><th>Num1</th><th></th><th>Num2</th></tr>' +  
  37.                     '<tr><td> <input type="number" ng-model="calcu.num1" /></td>' +  
  38.                     '<td style="width:20px;" valign="middle"> <h4>{{calcu.act}}</h4> </td>' +  
  39.                     '<td> <input type="number" ng-model="calcu.num2" /> </td>' +  
  40.                     '<td align="center">' +                          
  41.                     '</tr><tr><td colspan="3"><button data-ng-click="ActAdd(calcu)">+</button>' +  
  42.                     '<button data-ng-click="ActSubtract(calcu)">-</button>' +  
  43.                     '<button data-ng-click="ActMultiply(calcu)">x</button>' +  
  44.                     '<button data-ng-click="ActDivide(calcu)">/</button>' +  
  45.                     '<button data-ng-click="ActClear(calcu)">Clear</button>' +  
  46.                     '</td></tr>'+  
  47.                     '</table><h3>{{calcu.res}}</h3>' +  
  48.                     '</div>' +  
  49.                     '</div>'  
  50.             }  
  51.         });  
  52.     myApp.directive('interestCalculator',function(){  
  53.         return {  
  54.                 restrict: 'AE',  
  55.                 link:function($scope){  
  56.                     $scope.ActSimpleInt = function (calint) {  
  57.                         calint.res = Number(calint.principal) * Number(calint.months)* Number(calint.rate/100);  
  58.                     }  
  59.                     $scope.ActCompoundInt = function (calint) {  
  60.                         var res1=Math.pow(((1+((Number(calint.rate)/100.0)/Number(calint.months)))),Number(calint.months));  
  61.                         calint.res =Number(calint.principal)*res1;                              
  62.                     }  
  63.                 },  
  64.                 template:  
  65.                     '<div class="container" style="width:600px;" ng-init="calint={principal:0, months:0, rate:0.0 ,res:0}">' +  
  66.                     '<div id="calintsc" class="row">' +                          
  67.                     '<table table table-condensed id="tbltwo">' +  
  68.                     '<tr><th colspan="3"><h2>Interest Calulator</h2></th></tr>'+  
  69.                     '<tr><th>Principal</th><th>Months</th><th>Rate(%)</th></tr>' +  
  70.                     '<tr><td> <input ng-model="calint.principal" /></td>' +  
  71.                     '<td> <input ng-model="calint.months" /> </td>' +  
  72.                     '<td> <input ng-model="calint.rate" /> </td>' +  
  73.                     '</tr><tr><td align="center" id="rbtnintc" colspan="3">' +  
  74.                     '<button data-ng-click="ActSimpleInt(calint)">Simple Interest</button>' +  
  75.                     '<button data-ng-click="ActCompoundInt(calint)">Compound Interest</button>' +  
  76.                     '</td></tr>' +  
  77.                     '<tr><td colspan="3"><h3>{{calint.res|number:2}}</h3></td></tr></table>' +  
  78.                     '</div></div>'  
  79.             }  
  80.     });  
  81.     myApp.controller('myDirtveCtrl'function ($scope) {  
  82.         });  
  83. </script>  
Section 2
Section 2 is the HTML code part. To call a directive in our page, it is very simple. If you want to use it as an element in our program just write something like <directive-name></directive-name>. In our case, the name is <interest-calculator><interest-calculator/>. If you wan't to use as attribute in our program, just write something like <div directive-name></div>. In our case, the name is <div my-calcutator></div>.
  1. <body ng-controller="myDirtveCtrl">     
  2. <table width="75%">    
  3.     <tr><td colspan="2" align="center"><h1><u>Angular Js Custom Directive for Beginner</u></h1></td></tr>    
  4.     <tr>    
  5.         <td><interest-calculator></interest-calculator></td>    
  6.         <td><div my-calcutator></div></td>            
  7.     </tr>    
  8. </table>    
  9. </body>     


This article showed and explained to beginners how to create a custom directive in Angular js. A directive is a way to create a custom element with its own behavior, which we can then use later as a building block in our application.