Monday, 11 April 2016

Know your Directives : Novice II

In this blog I will explain about different types of Directives. This is somewhat less talked about but a very important concept.

You guy have been using directives as attributes like ng-app,  ng-controller, ng-click etc. Also in my last post you learned about directive being created as custom element. But why do we need different ways of specifying directive?
What is the difference between specifying a directive as an attribute and as an custom element?
We use directive as an attribute when we want to modify something in our html tag like ng-show adds a property to hide or display a template, ng-click add a functionality to a element where as we use directive as an custom element when we want to add something new in our template like our display-info directive.
Lets move on to see different types of directives.

Types of Directives

    Component Directive:
    These are kind of widgets.We can put it wherever we want and it will add new functionality in that place of the page. display-info that I created in my last blog its a component directive. These directives are mostly implemented as custom element.
    Decorative Directive:
    These directives modifies existing tag in our template like adding a new functionality or property.These are mostly implemented as attribute.
    Structural Directive:
    These directives display data by manipulating structure of DOM like ng-repeat.

Naming Directives

It is a good practice to name your directive with some prefix. For example <omi-display-info>. So you always have to prefix your directive with omi which is my name... lol don't worry I am kidding. You can prefix it with whatever you want but important part is why do we need to do so?
So here is couple of reason.
First who knows a new tag <display-info> is created for html in future. You are a programmer and even if its one way road you cross it by looking at both the sides!
Second who knows if your code falls into a hand of a psychopath? He should definitely find your code readable and have no ambiguity about your directive being a html tag!
I won't be using prefixes but you should absolutely use it specially if your code is in production!
Now you are no more a Novice.Its high time we go to some advance level.In my next blog we will go deeper and see how to integrate scope,controller,events with directive.Yes I do remember the question I put on in my previous blog and we are going to solve that problem in my next blog.

No comments:

Post a Comment