Learn AngularJS: Episode 3 of 15

Learn AngularJs: Episode 1: Click here
Learn AngularJs: Episode 2: Click here

We'll cover the following topics in this article:

  • AngularJs Directive
  • Built-in Directives
  • Examples of few directives
  • Creating Directive
  • AngularJs Custom Directive
  • Creating Custom Directive

AngularJs Directives

  • Core AngularJs feature / JavaScript function
  • Invoked when the DOM is compiled by the AngularJs framework
  • Extends the HTML by adding attributes (specific to the application)
  • Used to develop custom elements (specific to the application) or
  • Makes the HTML DOM more flexible by allowing developers to build custom tree nodes
  • Simplifies Document Object Model (DOM) manipulation
  • Controls the HTML rendering within an AngularJs application
  • It specifies how to mix the data into the HTML template (data binding)
  • Can implement directives as:

       - Element directives (recommended)
       - Attribute directives (recommended)
       - CSS class directives (avoid until necessary)
       - Comment directives (avoid until necessary)

Built-in Directives

The AngularJs Framework provides a variety of built-in directives. The built-in directives have the "ng-" prefix.

A few of the most commonly used built-in directives are:

Directives Description

ng-app

Root element for AngularJs app. Auto-bootstrap the application.

ng-init

Initialize app data and evaluate an expression

ng-model

Binds view into the model

ng-controller

Attach controller class to view

ng-repeat

Iterates the collection and instantiate template for each iteration

ng-bind

Binds the value of the given expression to the specified HTML element

ng-bind-template

Binds the value of {{multiple}} {{given}} {{expressions}}

ng-show, ng-hide

Shows or hides the HTML element based on the given expression

ng-click

Used to specify custom behaviour when an element is clicked

ng-non-bindable

To ignore binding expression

Example of commonly used directives

I've used Visual Studio Code as an editor and AngularJs v1.3.15 as Angular framework.

I've picked up a few code snippets from source code as in the following:

  1. <html ng-app="appModule">  
  2. <button ng-click="rating=rating+2;" ng-init="1">Give Rating</button>  
  3. <label>Hide Educational Information?   
  4. <input type="checkbox" ng-model="HideEduInfo" /></label>  
  5.   
  6. <label>Show Other Staff Details?  
  7. <input type="checkbox" ng-model="ShowOtherStaff" /></label>  
  8. <div ng-controller="personalInfoController">  
  9. <span ng-non-bindable><strong>{{Email}}</strong></span>  
  10. <div ng-controller="educationInfoController" ng-hide="HideEduInfo">  

Why to create a new directive

New directives are created so that the developers can modify the existing behaviour of elements, build more complex components using proper semantics or use to encapsulate logic and simplify DOM manipulation. Refer to the definition section above.

If you are familiar with how to create an AngularJs controller, the job is half done. Creating a directive is quite similar to creating a controller.

Syntax

Minimum requirement:

  1. module.directive("directiveName", function () {  
  2.     return {  
  3.   
  4.     };  
  5. });  

My Custom Directive

There is a similar example given in Episode3.html where there is no custom directive used. I have prepared the same example using my very own directive. Here we go:

  1. appModule.directive("ratingdirective", function () {  
  2.     return {  
  3.     template: "<span> Hey Reader! This is my custom directive.</span>" +  
  4.               "<span> Do you like it?</span><br />" +  
  5.               "<button ng-click='customrating=customrating+1;' ng-init='1'>  
  6. Give Rating</button>" +  
  7.               "<span>Your rating count is {{customrating}}</span><br />"  
  8.     };  
  9. });  

Eventually, we can do the similar operation in a custom directive as we do in the normal course of coding. There may be some scenarios where, as a developer, you wish to reutilize the similar pattern or template on a web page so instead of repeating the code, we smartly keep the template in a custom directive.

There is no wonder in creating custom directives. Please look at the preceding example and notice that I have used template in this example and I also have used a built-in directive. I thought of creating a rating directive that could allow application visitors to provide a rating and moreover the same snippet could also be used in multiple places in a web page. I believe custom directives can help me in reutilization of the same piece of code at a different level. This provides cleaner code and eliminates redundant coding.

Developers are free to write their own snippet (template). This is just a basic example of creating your own directive. Here are a couple of other examples:

  1. appModule.directive("ratingdirective", function () {  
  2.     return {  
  3.     restrict:'AE', //this can be used as attribute and independent element only  
  4.     template: "<span> Hey Reader! This is my custom directive.</span>" +  
  5.               "<span> Do you like it?</span><br />" +  
  6.               "<button ng-click='customrating=customrating+1;' ng-init='1'>Give                 Rating</button>" +  
  7.               "<span>Your rating count is {{customrating}}</span><br />"  
  8.     };  
  9. });  

Significance of the "restrict" property

The following describes the significance of the "restrict" property:

Restrict

Value

How to use?

Attribute

A

Use as an attribute of any container element (default and recommended)

<div yourDirectiveName>

Element

E

Use as an independent user defined element (recommended)

<yourDirectiveName>

Class

C

Use as CSS class name in any container element (not recommended)

<div class=" yourDirectiveName ">

Comment

M

Use as HTML comment (not recommended)

<!-- yourDirectiveName -->

In case your desired HTML template code is isolated in another .html file, you can assign the URL of that file using the templateUrl property.

File Name: customdirective.js

  1. appModule.directive("mydirective", function () {  
  2.     return {  
  3.     restrict:'AE', //this can be used as attribute and independent element only  
  4.     templateUrl:'rating.html' //this file is available separately  
  5.     };  
  6. });  

File Name: rating.html

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title></title>  
  5. </head>  
  6. <body>  
  7.     <span> Hey Reader! This is my custom directive.</span>  
  8.     <span> Do you like it?</span><br />  
  9.     <button ng-click='customrating=customrating+1;' ng-init='1'>Give Rating</button>  
  10.     <span>Your rating count is {{customrating}}</span><br />  
  11. </body>  
  12. </html  

I believe this is enough material to kick-off the directive. Though it has a lot of scope, it could be learned by practice.

Happy learning.

Episode 4 : AngularJs Services (coming next shortly)

Up Next
    Ebook Download
    View all
    Learn
    View all