Click here to Skip to main content
15,867,330 members
Articles / Web Development / HTML

Learning AngularJs - Episode 3 of 15

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
9 May 2015CPOL2 min read 16.9K   106   16   4
Part 3 of learning AngularJS

Revisit Episode 1: Click here

Revisit Episode 2: Click here

Introduction

We'll cover the following topics in this writing:

  • 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 DOM is compiled by AngularJs framework
  • Extends the HTML by adding attributes (specific to application)
  • Used to develop custom elements (specific to application) Or
  • Make the HTML DOM more flexible by allowing developers to build custom tree nodes
  • Simplifies Document Object Model (DOM) manipulation
  • Controls the HTML rendering within AngularJs application
  • It tells 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

AngularJs Framework provides variety of built-in directives. The built-in directives has "ng-" as prefix.

Few of the most commonly used built-in directives are:

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 Bind the value of given expression to the specified HTML element
ng-bind-template Bind the value of {{multiple}} {{given}} {{expressions}}
ng-show, ng-hide Show or hide the HTML element based on given expression
ng-click Used to specify custom behaviour when 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 few code snippets from source code and highlighted the directives.

HTML
<htmlng-app="appModule">
<buttonng-click="rating=rating+2;"ng-init="1">Give Rating</button>
<label>Hide Educational Information? 
<inputtype="checkbox"ng-model="HideEduInfo"/></label>

<label>Show Other Staff Details?
<inputtype="checkbox"ng-model="ShowOtherStaff"/></label>
<divng-controller="personalInfoController">
<spanng-non-bindable><strong>{{Email}}</strong></span>
<divng-controller="educationInfoController"ng-hide="HideEduInfo">

Why do we create a new directive?

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 the definition section above.

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

Syntax

Minimum requirement:

module.directive("directiveName", function() {
return{
};
});

My Custom Directive

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

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

Significance of 'restrict' Property

Restrict Value How to use?

Attribute

A

Use as attribute of any container element [Default and recommended]

HTML
<div yourDirectiveName>

Element

E

Use as independent user defined element [Recommended]

HTML
<yourDirectiveName>

Class

C

Use as CSS class name in any container element [Not recommended]

HTML
<div class=" yourDirectiveName ">

Comment

M

Use as HTML comment [Not recommended]

JavaScript
<!-- yourDirectiveName -->

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

File Name: customdirective.js

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

File Name: rating.html

HTML
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<span>Hey Reader! This is my custom directive.</span>
<span>Do you like it?</span><br/>
<buttonng-click='customrating=customrating+1;'ng-init='1'>Give Rating</button>
<span>Your rating count is {{customrating}}</span><br/>
</body>
?</html>

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

Happy learning...

Episode 4 : AngularJs Services (coming next shortly)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Project Manager in MNC. Having 12 years of corporate experience mostly in Microsoft Technologies. Developer by passion. A happy husband and father of two lovely kids.
Like writing, association of professionals, leadership, public speaking.

Comments and Discussions

 
GeneralMy vote is 5- Good article on angularJS Pin
Member 1101231317-Oct-15 18:55
Member 1101231317-Oct-15 18:55 
GeneralRe: My vote is 5- Good article on angularJS Pin
Abhishek Maitrey15-Dec-15 19:12
Abhishek Maitrey15-Dec-15 19:12 
Thanks for your message. I'm in middle of writing another piece of articles but assure you to be back with remaining episodes.

Many thanks again.
Abhishek Maitrey
@abhimaitrey

GeneralMy vote of 5 Pin
Member 1101231317-Oct-15 18:50
Member 1101231317-Oct-15 18:50 
GeneralRe: My vote of 5 Pin
Abhishek Maitrey15-Dec-15 19:13
Abhishek Maitrey15-Dec-15 19:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.