AngularJs Directives

AngularJs directives are an extension over the HTML that let you extend the HTML DOM to add the special behavior to it.

If you have created any application using AngularJs, you have used AngularJs directives in that whether you have realized it or not. You might have used simple directives like ‘ng-app’, ‘ng-model’, ‘ng-repeat’, ’ng-controller’ etc.




What all these directives do?

Well, they attach special behavior to the HTML elements for example ‘ng-app’ attaches the behavior to identify which part of HTML contains AngularJs app.

The Type of Directives:

1.    Interpolation Directive:  In AngularJs while we use any expression we write them in double curly braces “{{ }}” so this double curly braces is also known as interpolation directive.

2.    “ng-bind” Directive:  “ng-bind” as the name suggest is used to bind/replace text content of any particular HTML element with the value of given expression that is used against the ng-bind. The value of the specified HTML element will be updated whenever the value of given expression will be changes.

The Example code as given below

The AngularJs code sample
                 var app = angular.module("AngularApp", []);
                       app.controller("HelloController", function ($scope) {
                       $scope.text = "";
    });

The AngularJs HTML code sample
               <div ng-app="AngularApp">
                  <div ng-controller="HelloController">
                      Enter anything you want to display: <input type="text" ng-model="text">
                      You entered : <span ng-bind="text"></span>
                 </div>
</div>
            The full example code as given below
            <!DOCTYPE html>
<html lang="en">

<head>
    <title>Angular Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" type="text/javascript" charset="utf-8"></script>
    <script>
        var app = angular.module("AngularApp", []);
        app.controller("HelloController", function ($scope) {
            $scope.text = "";
        });
  </script>
</head>

<body ng-app="AngularApp">
    <div ng-controller="HelloController">
        Enter anything you want to display :
        <input type="text" ng-model="text">you entered : <span ng-bind="text"></span>
    </div>
</body>
</html>

 The output: go to below link
http://plnkr.co/edit/wVrKFvkihBM5dtwaAmFM?p=preview


3.    “ng-view” and “ng-template” Directive:  “ng-view” directive is used to switch between views in AngularJs. The example as given below.

           The AngularJs code sample
        var app = angular.module("AngularApp",['ngRoute']);
        app.config(['$routeProvider'function($routeProvider) {
            $routeProvider.when('/', {
                templateUrl: 'test.html',
                controller: 'testCtrl'
            })
        }
        ]);

        app.controller("testCtrl", function($scope){
            $scope.model= {
                text:"This is the example of ng-view in angular js"
            }
      });

The HTML code sample
              <div ng-app="AngularApp">
                    <ng-view></ng-view>
   </div>

The example for full code is below
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Angular Demo</title>
    <script src="angular.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="angular-route.min.js" type="text/javascript" charset="utf-8"></script>
    <script>
        varmyApp = angular.module("AngularApp", ['ngRoute']);
        myApp.config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.when('/', {
                templateUrl: 'test.html',
                controller: 'testCtrl'
            })
        }
        ]);
        myApp.controller("testCtrl", function ($scope) {
            $scope.model = {
                text: "This is the example of ng-view in angular js"
            }
        });
    </script>
</head>

<body ng-app="AngularApp">
    <ng-view></ng-view>
</body>
</html>

The output: go to below link
http://plnkr.co/edit/3fBAXfAe7qowY14R2Mz7?p=preview

The “ng-template” directive:

The “ng-template” directive is used to load the content of a <script> element into $templateCache, and this is done to further used by ng-Include, ng-View, template etc.

There is one rule which we must have to follow when we use ng-template directive and that is the type of the <script> element must be specified astext/ng-template, and a cache name for the template must be assigned through the element's id, which can then be used as a directive's templateUrl.

The Example code as given below

The AngularJs code sample
        var app = angular.module("AngularApp", ['ngRoute']);
           app.config(['$routeProvider', function ($routeProvider) {
            $routeProvider.when('/test1', { templateUrl: 'test1.html' })
                    .when('/test2', { templateUrl: 'test2.html' })
                    .when('/test3', { templateUrl: 'test3.html' });
        }
        ]);

         app.controller('exampleController', function ($scope) {
            $scope.text = 'Hello';
   });

The HTML code sample
<div ng-app="AngularApp">
    <div ng-controller="exampleController">
        <script type="text/ng-template" id="test1.html">
This list denotes the first list element.
        </script>
        <script type="text/ng-template" id="test2.html">
<h3>This is the header of the second list.</h3>
        </script>
        <script type="text/ng-template" id="test3.html">
<b>The ng-template directive is magical</b>
        </script>
        <ul>
            <li><a href="#/test1">list1</a></li>
            <li><a href="#/test2">list2</a></li>
            <li><a href="#/test3">list3</a></li>
        </ul>
        <div ng-view>
            Loading...
        </div>
    </div>
</div>

In the above example we have used ng-template in script tag to load the HTML.
It contains "id" attribute which is used by $routeProvider to map the view with a controller.

The output: go to below link
http://plnkr.co/edit/Wnkvt8lECI9hiTqmj8JB?p=preview


4.    Escaping HTML from the model:

What is HTML escaping?

Well, in HTML there are many super characters like: <, >, &, and ". When using these characters, it is very important to know let HTML know if we want to use them normally or in their special capacity.

In AngularJs if the data received from the model contains HTML elements then this should be escaped before inserting into the HTML template to the view. This is done to prevent the HTML injection attacks.

Suppose we have an image tag like below

<imgsrc="photo.jpg"alt="Indonesian Phrase of the Day: "Selamatpagi"" />
The value of the alt attribute will be displayed on the HTML in weird format. The first quotation of the alt tag will be treated as closing quote. To escape the same kind of problem angular provides some directive to escape the HTML.

Angular provides $sce and ng-bind-html directives to HTML escaping.

A nice read on HTML escaping in AngularJs go to below link
https://docs.angularjs.org/api/ngSanitize/service/$sanitize.

5.    Conditional Rendering: as the name itself is describing here the conditional rendering is like rendering of the HTML DOM based on the state of the data model i.e. if, else if, else conditions. The same will be covered in further ng-show and ng-hide directives sections.

6.    “ng-show” and “ng-hide” Directives: The “ng-show” and “ng-hide” directive takes control of displaying HTML element on the browser. They will be shown and hidden on the browser depending on the value of their corresponding data model values.

The Example code as given below

The AngularJs code sample
        var app = angular.module("AngularApp", ['ngRoute']);
        app.controller('exampleController', function ($scope) {
            $scope.textVal = "";
            $scope.isOK = function (param) {
                if (param == "show") {
                    returntrue
                }
                else if (param == "hide") {
                    returnfalse
                }
                else {
                    returntrue;
                }
            }
        });
The HTML code sample
             <div ng-app="AngularApp">
    <div ng-controller="exampleController">
       <label>Please enter show and hide to show hide the element below : </label>
       <input ng-model="textVal">
       <div ng-show="isOK(textVal)">The Div is displaying now</div>
    </div>
</div>

The full example code as given below
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Angular Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
    <script>
        var app = angular.module("AngularApp", ['ngRoute']);
        app.controller('exampleController', function ($scope) {
            $scope.textVal = "";
            $scope.isOK = function (param) {
                if (param == "show") {
                    returntrue
                }
                else if (param == "hide") {
                    returnfalse
                }
                else {
                    returntrue;
                }
            }
        });
    </script>
</head>
<body ng-app="AngularApp">
    <div ng-controller="exampleController">
        <label>Please enter show and hide to show hide the element below : </label>
        <input ng-model="textVal">
        <div ng-show="isOK(textVal)">The Div is displaying now</div>
    </div>
</body>
</html>

In the above example the div is binded by ng-show directive that is dependent on the model state of isOK, if the value of this will be true then the div will be shown else it will be hidden.

Just type show in the input field and you can see the div shown.

The Live output: go to link
http://plnkr.co/edit/VyjZjLXuqACtNL0JPM9h?p=preview


7.    “ng-switch” directive: “ng-switch” directive is used to behave similar to the switch case in general programming scenario. In AngularJs ng-switch is used to swap between the HTML DOM elements bases on the data model wrote in the expression.

The live example code as given below

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Angular Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
    <script>
        var app = angular.module("AngularApp", ['ngRoute']);
        app.controller("exampleCtrl", function ($scope) {
            $scope.switchVal = {};
            $scope.switchVal.exactVal = "one"
        });
    </script>
</head>

<body ng-app="AngularApp">
    <div ng-controller="exampleCtrl">
        <div ng-switch on="switchVal.exactVal">
            <div ng-switch-when="one">You wanted to show first div since you have entered one.</div>
            <div ng-switch-when="two">You wanted to show second div since you have entered two.</div>
            <div ng-switch-when="three">You wanted to show third div since you have entered three.</div>
            <div ng-switch-default>You are in default switch case.</div>
        </div>
    </div>
</body>
</html>

In the example above we have we have defined a div elements with an ng-switch attribute and on attribute.

The on attribute tell on which data of the model the switch will be applied on. Inside the switch element we have three <div> elements.

The first two elements have the attribute “ng-switch-when” and the last div element have the attribute ng-switch-default. They act same as the switch case.

If the related data model contains the value matched to the given value then the respective div will be shown else the default div will be shown.

The Live output: go to link
http://plnkr.co/edit/CVKDyFTJqFVJpqDaor0c?p=preview


8.    The “ng-if” Directive: the “ng-if” directive in AngularJs is used to remove and reinsert portion HTML DOM element into a HTML template tree. This is executed based on the value of expression assigned to the “ng-if” attribute.

Now the question is – what is the difference between “ng-if” and “ng-show/ng-hide” then. Since they all do the same thing on the browser. Well, the difference is – the “ng-show/ng-hide” just do the display and hide of the HTML element by manipulation the display property of the CSS whereas the “ng-if” completely remove and recreate the HTML portion from the HTML DOM tree.

The live example code as given below

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Angular Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
    <script>
        var app = angular.module("AngularApp", ['ngRoute']);
        app.controller('exampleController', function ($scope) {
            $scope.textVal = "";
            $scope.isOK = function (param) {
                if (param == "show") {
                    returntrue
                }
                else if (param == "hide") {
                    returnfalse
                }
                else {
                    returntrue;
                }
            }
        });
    </script>
</head>

<body ng-app="AngularApp">
    <div ng-controller="exampleController">
        <label>Please enter show and hide to show hide the element below : </label>
        <input ng-model="textVal">
        <div ng-if="isOK(textVal)">The Div is displaying now</div>
    </div>
</body>
</html>

The above example is same example as the “ng-show” example; the change is just the attribute. We have replaced the “ng-switch” attribute by “ng-if”.

The same way we can understand the “ng-else-if” and “ng-else” as well. We can define the expression in the attribute and they will execute accordingly.

The Live demo example: go to link
http://plnkr.co/edit/SIiXEIVnhBZEaXSeiB6y?p=preview


9.    The “ng-include” Directive: Since we know that embedding HTML pages in HTML pages is not supported in HTML. To achieve this we need to follow some custom approaches like Ajax and including HTML via server side programming.

 The code look like

<div ng-include src="'views/index.html'" />

AngularJs give the functionality to embed external HTML into HTML by using “ng-include”. The “ng-include” fetches, compiles and includes an external HTML fragment.

The example code as given below.

<html>
<head>
    <title>using Angular ng-Include</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script>
        var app = angular.module("ngApp", []);
        app.controller('ngController', function ($scope) {
            $scope.users = {
                fName: "Anil",
                lName: "Singh",
                age: 30,
            };
        });
    </script>
</head>
<body ng-app="ngApp">
    <div ng-controller="ngController">
        <div ng-include="'views/main.html'"></div>
        <div ng-include="'views/users.html'"></div>
    </div>
</body>
</html>

For output : go to below link
http://embed.plnkr.co/058uRe/preview


10.  The “ng-cloak” Directive: The ng-cloak is a special type of directive with used to which used to prevent un-compile element being displayed. We can say that ng-cloak directive hold and wait to incoming data's.

The ng-cloak look like below code.

<div ng-cloack>
    <div ng-if="!users.isValid">
        {{ name }}
    </div>
</div>

In the above code sample, ng-cloak directive prevent to display un-compiled user name and Its not displayed before compile the user name.

·         Without using the ng-cloak the output will display the {{ name }}
·         With using the ng-cloak the output will display blank.

The example code as given below.
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Using ng-cloak directive </title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script>
        var app = angular.module("ngApp", []);
        app.controller('ngController', function ($scope) {
            $scope.name = "Anil Singh";

            $scope.users = {
                isValid: true
            };

        });
    </script>
</head>
<body ng-app="ngApp">
    <div ng-controller="ngController">
        <div ng-cloak ng-if="!users.isValid">
            {{ name}}
        </div>
    </div>
</body>
</html>

For the output : go to below link









About Blogger

ANIL SINGH

Hey! I am Anil Singh. I am Active Blogger, Writer and Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
http://www.code-sample.com
http://www.code-sample.xyz

    Blogger Comment
    Facebook Comment

1 comments:

  1. very informative & different one....
    I would like to share the information to get jobs easily
    Angularjs Training In Hyderabad

    ReplyDelete

SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book