In this tutorial, we will be learning the basics of creating custom directives in angular js.
A lot of angular beginners think custom directives are high level stuffs and are difficult to understand and hence they leave it for later study.If that’s the case with you , this tutorial will change the way you think about custom directives in angular js.
var testApp = angular.module('testApp',);
Here testApp is your angular application or module , and to it we attach our directive.myDirective would be the name of your directive.Notice we have used camel case syntax for the name.
Now we have to invoke our directive into our DOM.This is how we would do it.
Notice in the name <my-directive>, the camel casing is replaced with a dash.This is important for a directive to work.
Although now we have our directive, it would do just nothing as we haven’t specified any options to it.Lets do it here.
Add this to the returning object inside the directive.
restrict:’AEC’– This restricts the way in which the directive can be invoked in html.
“A” stands for attribute, “E” stands for element and “C” stands for class.
So in our case we can use our directive as an attribute, an element and as well as a class.
See below for reference.
Invoked as an element
Invoked as a class
Invoked as an attribute
We have also specified a template,(template:'<label>My Directive: <input type=”text” class=”form-control”/><label>’)this template will be rendered in our DOM where we use our directive.
You might have just started to know how awesome angular custom directives can be , because here,now you can use this template at multiple places without having to re-write the code.
Note, instead of a template you can also specify a URL to fetch the html template.
Use templateUrl instead of template.
I already have a simple template which displays user’s face and has a css3 fade out transition, which I would like to use at multiple places in my application.
See the Demo : here
Download Code : here
In this demo the black image strip is a directive with a templateUrl,this directive is used at two places.
Also to note, this demo is to demonstrate the basics of directive,in practice the dom manipulation should also be inside the directive and there is no need of using jquery for it.
To learn how to create this css3 fade out animation visit here
You can also access the scope of the controller in which the directive is invoked.
Directives can have their own separate controllers as well.
We have just scratched the surface of custom directives in angularjs .In our later tutorials We’ll show you how to attach a controller to the directive and also how to dynamically attach controllers to a single directive and using scope and isolating scopes.
This was a great tutorial and very comprehensive! Thanks man! Keep up the good work
Your welcome Andrey, glad that you found this useful.
I’m in process of writing another tutorial related to the same.