Saturday, 9 April 2016

First Directive : Novice I

I started learning angular few months back. I found it useful but not a great leap forward until I came across Angular Directives.
So what are Directives? To put it in a very simple way, they are just marker on your html that tells Angular to modify or replace the code with JavaScript.
We do that by creating a new attribute or custom html elements.
Creating our own html elements!isn't that supercool? Oh yes!boy
So let the game begin...

How do we create directives?

There are four ways of specifying directive :
  • As a custom element
  • As an attribute
  • As a class
  • As a comment

The first two methods are the recommended way and I am going to cover those only.So Lets move on to create our first directive.  Now lets review what I have done.
Inside my body tag I have created a custom element, display-info
Now my DOM is marked with an element which will tell Angular JS to replace it with some JavaScript code and we are going to do that by creating a directive with name displayInfo.
Notice that I have put name of directive in camel case but my custom element is separated with dash.This is to support case insensitivity of html.

<body ng-controller="mainCtrl">
    <display-info></display-info>
</body>

angular.module('myApp').directive('displayInfo', function() {
  return {
template: "Name: {{user.name}}<br/>Address:<br/>Street : {{user.address.street}},
    restrict: "E"
  }
});

template is where you add your data which will replace the custom element in your html.In template element you can bind any object or write html code.But the problem with this is as you go on nesting your code your template become messy and unreadable. This is where templateUrl comes to rescue.Just write you html code in a new file and let your template know about it!

angular.module('myApp').directive('displayInfo', function() {
  return {
    templateUrl: "displayInfo.html",
    restrict: "E"
  }
});

Before you start wondering what this restrict property does, let me tell you its just for letting Angular know what kind of directive you want? For elements its "E", for attribute its "A", for class its "C" and for comments its "M" and you can even combine them like, restrict: "AEC".
See its that easy!
Now I want you guys to think about something.What if I want to use same directive in our page? Quiet obvious it will display same data as they share same scope. So think, if its possible where we can have same directive in a page displaying two different data?
In my next blog I am going to take you guys to next level.We will see what are different types of directives, and lets see if we can solve the problem I just mentioned above!

No comments:

Post a Comment