AngularJS Directives, Demystified


First thing to grasp in AngularJS is that it's not a jargon. Every concept in Angular is already there in JavaScript or in other libraries. Keep reading.

What is a Directive in AngularJS?

Well, according to AngularJS documentation Directives are Marker such as Element, Attribute, CSS class or even comment in the DOM element which tell HTML compiler to attach specific behaviour to DOM element or even modify them.

That sounds good, but how is it possible to create a custom HTML. Something like <superman></superman>. Well there is a provision in HTML 5 to create a custom element, which you can learn here.

Saying that, it is very easy to define our own custom element by simply creating a new directive and restricting it to "E", i.e. Element.

We will learn more in the later post where I'll show you how to create your own Directives. Other than element directives you can create an attribute directive or a class directive or comment directive.

Directive tells the compiler to attach the specific behaviour. For example you would select a class "slider" and attach the special method called "horizontalSlider" in jQuery to retrieve the properties of the element and append the images retrieved using the AJAX.

$(".slider"). horizontalSlider();


Where $ is the jQuery object and horizontalSlider is method in that object. Similarly, in Angular we directly build the custom element to attach the behaviour. Where creating an element is a new feature.

Following is the animation which will explain how does Angular compiles or parses the DOM to find the directives. Follow the blue cursors and bottom terminal to know the current state of the parser. Start reading when Terminal says HTML Compiler > init. 

Disclaimer: This is just the representation for the sake of explanation, the actual process may be different.

The directives which you are seeing in above animation are default directives of AngularJS. Following are few of the common directives we will come across.

  1. ng-app
  2. ng-controller
  3. ng-model
  4. ng-init
  5. ng-bind
  6. ng-view
  7. ng-click
At this point I guess, you are good to go with the directives. Let's dive into the official documentation for directives here.

The one which you see in double curly braces {{}} are expressions. Which we will see later.

Angular Basics, create Hello World

  • Context: Angular JS Tutorials
  • Level: Beginner
  • Difficulty Scale: 1/10

What is AngularJS?

AngularJS is the versatile JavaScript MVC framework for creating Web Application. It gives you the flexibility to change the view, write the controller and interact with data model on the go.

 Many developer prefer calling it a "two-way data binding", which however is true because it binds the model with the view and augment the DOM hierarchy using the "scope" within the controller.

You will learn more about each of the fundamental aspects of Angular such as Model, View, Controller, Scope, root Scope etc.

 For now, fire up your favourite code editor and throw in the AngularJS file and bootstrap's CSS file to help you build the application further.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello World using Angular JS: Consolidatedjs.com</title>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/assets/css/bootstrap.min.css">
</head>
<body>
  <!-- Our Code goes here -->
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
</body>
</html>
With the above code in your code editor and save the file as index.html, we are good to go. Now, insert the following code.
<div class="container">
  <div data-ng-app>
    <input type="text" data-ng-model="name">
    <h2>Hello {{name}}</h2>
  </div>
</div>


Full Code

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello World using Angular JS: Consolidatedjs.com</title>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/assets/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div data-ng-app>
      <input type="text" data-ng-model="name">
      <h2>Hello {{name}}</h2>
    </div>
  </div>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
</body>
</html>

Well, what does it do?

Hmmm, thanks for the patience! Here's what we have done so far.
  • We created a div with the class "container", which is bootstrap class for wrapper
  • Then we created a div with attribute data-ng-app, which however is angular JS directive which tells AngularJS's HTML compiler that this is the beginning of our Angular App and it creates scope object to hold the context of our application.
  • Once we made a context for rest of the app using data-ng-app, we then created a simple HTML input tag to hold the model using data-ng-model
  • Now, we bind the expression name using curly braces. Expression in Angular is similar to JavaScript expression which binds with the context, in our case the context is Application using the scope object. Don't worry, you learn more about this in later sessions.
Now, open the index.html in your web browser and Hurray! We built our first AngularJS Application.

Type in your name in the text box and surprise, the expression below will evaluate your name in real time. This is what we call two-way data binding.

You can see, that we didn't included any JavaScript and yet we have accomplished something which we would have written lines of code in jQuery, dojo or any other JavaScript Library. This is power of the directives in AngularJS.

Demo

 Following is the demo to feed your curiosity.

Swap two variables in JavaScript

Swapping two numbers in JavaScript is easy. There are few methods to do it. However, EcamScript 6 standard came up with a better solution which we will see later in this post. Following are the methods.

Method 1: Using third variable

This method is the conventional technique in any programming language. We will create third variable to store one of the variable value.
 var a = 2, b = 3, var c;

 var c = a;
 a = b;
 b = c;

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Method 2: Using the Equation

 var a = 2, b = 3;
 
 a = a+b;
 b = a-b;
 a = a-b;

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Method 3: Using Array

 var a = 2, b = 3;
 
 a = [b, b=a][0];

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

Method 4: EcmaScript 6

 var a = 2, b = 3;
 
 [a,b] = [b,a];

 console.log("a: " + a);
 console.log("b: " + b);

Output

 a: 3
 b: 2

AngularJS Video Tutorials

Following are the collections of best video tutorials for AngularJS.
1. AngularJS Fundamentals In 60-ish Minutes By Dan Wahlin


2. Angular JS - The Basics for absolute Begginers By That JS Dude

Check the speed of execution in JavaScript

Following is the technique you can use to check the speed of code execution in JavaScript.

  var start = new Date().getTime();
  
  //sample code to test
  for(var i = 0; i <= 1000; i++){
    console.log("Test: " + i);
  }

  var elapsed = (new Date().getTime() - start) / 1000 + " Seconds";

  console.log(elapsed);

Code Explanation

First we create a variable called start and assign the current time using JavaScript's Data() method and get the time in seconds from year 1970 to present using getTime().

 Then write your JavaScript code(It can be anything). Just after your code create a new variable called elapsed and subtract the current time with the value stored in the variable start.

 The console will output the elapsed time in milliseconds, here I've divided the result by 1000 to convert it into the seconds. Following is the screenshot of the Chrome's Web inspector.


Hope this will help you in estimating the code performance. 

If you like this post, then please share your thoughts on how to reduce the execution time or some other techniques you use during the front end development.

Welcome to ConsolidateJS

Dear Reader, My name is Tirumal Rao and I am a front end developer. This blog is the all about nitty-gritty of JavaScript and it's applications. My work usually includes JS and it's framework or library.

There is lot to discuss, hope you enjoy reading my blog as much as I enjoy writing it.

Thanks,
Tirumal