Angular Custom Directives for Beginners

Introduction

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

code-beginner

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. 

<!DOCTYPE html>    
<html ng-app="myApp">    
<head>    
    <link href="bootstrap.min.css" rel="stylesheet" />    
    <script src="angular.min.js"></script>    
    <title>AngularJS Custom Directives</title>    
    <style type="text/css">    
    <!-- style in source code section-->        
    </style>    
    <script>    
    // script code below or available in source code.    
    </script>    
</head>    
<body ng-controller="myDirtveCtrl">     
</body>    
</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.

<script>  
     var myApp = angular.module('myApp', []);  
     // create directive  
    myApp.directive('myCalcutator',function(){  
            return {  
                restrict: 'AE',  
                link:function($scope){  
                      
                    $scope.ActAdd = function (calcu) {  
                        calcu.res = Number(calcu.num1) + Number(calcu.num2);  
                        calcu.act="+";  
                    }  
                    $scope.ActSubtract = function (calcu) {  
                        calcu.res = calcu.num1 - calcu.num2;  
                        calcu.act="-";  
                    }  
                    $scope.ActMultiply = function (calcu) {  
                        calcu.res = calcu.num1 * calcu.num2;  
                        calcu.act="x";  
                    }  
                    $scope.ActDivide = function (calcu) {  
                        calcu.res = calcu.num1 / calcu.num2;  
                        calcu.act="/";  
                        if(isNaN(calcu.res))calcu.res=0;  
                    }  
                    $scope.ActClear = function (calcu) {  
                        calcu.num1=0;calcu.num2=0;calcu.res=0;   
                        calcu.act="";                             
                    }  
                },  
                template:  
                    '<div class="container" style="width:300px;" ng-init="calcu={num1:0, num2:0,res:0}">' +  
                    '<div id="calcone" class="row">' +  
                    '<h2>Simple Calulator</h2>' +  
                    '<table table table-condensed >' +  
                    '<tr><th>Num1</th><th></th><th>Num2</th></tr>' +  
                    '<tr><td> <input type="number" ng-model="calcu.num1" /></td>' +  
                    '<td style="width:20px;" valign="middle"> <h4>{{calcu.act}}</h4> </td>' +  
                    '<td> <input type="number" ng-model="calcu.num2" /> </td>' +  
                    '<td align="center">' +                          
                    '</tr><tr><td colspan="3"><button data-ng-click="ActAdd(calcu)">+</button>' +  
                    '<button data-ng-click="ActSubtract(calcu)">-</button>' +  
                    '<button data-ng-click="ActMultiply(calcu)">x</button>' +  
                    '<button data-ng-click="ActDivide(calcu)">/</button>' +  
                    '<button data-ng-click="ActClear(calcu)">Clear</button>' +  
                    '</td></tr>'+  
                    '</table><h3>{{calcu.res}}</h3>' +  
                    '</div>' +  
                    '</div>'  
            }  
        });  
    myApp.directive('interestCalculator',function(){  
        return {  
                restrict: 'AE',  
                link:function($scope){  
                    $scope.ActSimpleInt = function (calint) {  
                        calint.res = Number(calint.principal) * Number(calint.months)* Number(calint.rate/100);  
                    }  
                    $scope.ActCompoundInt = function (calint) {  
                        var res1=Math.pow(((1+((Number(calint.rate)/100.0)/Number(calint.months)))),Number(calint.months));  
                        calint.res =Number(calint.principal)*res1;                              
                    }  
                },  
                template:  
                    '<div class="container" style="width:600px;" ng-init="calint={principal:0, months:0, rate:0.0 ,res:0}">' +  
                    '<div id="calintsc" class="row">' +                          
                    '<table table table-condensed id="tbltwo">' +  
                    '<tr><th colspan="3"><h2>Interest Calulator</h2></th></tr>'+  
                    '<tr><th>Principal</th><th>Months</th><th>Rate(%)</th></tr>' +  
                    '<tr><td> <input ng-model="calint.principal" /></td>' +  
                    '<td> <input ng-model="calint.months" /> </td>' +  
                    '<td> <input ng-model="calint.rate" /> </td>' +  
                    '</tr><tr><td align="center" id="rbtnintc" colspan="3">' +  
                    '<button data-ng-click="ActSimpleInt(calint)">Simple Interest</button>' +  
                    '<button data-ng-click="ActCompoundInt(calint)">Compound Interest</button>' +  
                    '</td></tr>' +  
                    '<tr><td colspan="3"><h3>{{calint.res|number:2}}</h3></td></tr></table>' +  
                    '</div></div>'  
            }  
    });  
    myApp.controller('myDirtveCtrl', function ($scope) {  
        });  
</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>.

<body ng-controller="myDirtveCtrl">     
<table width="75%">    
    <tr><td colspan="2" align="center"><h1><u>Angular Js Custom Directive for Beginner</u></h1></td></tr>    
    <tr>    
        <td><interest-calculator></interest-calculator></td>    
        <td><div my-calcutator></div></td>            
    </tr>    
</table>    
</body> 

Conclusion

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.