Building AngularJS Custom Directives

The people who are familiar with AngularJs applications must have used ng-app directive to initialize application, by default AngularJS framework comes with so many built in directives ex: ng-model, ng-app, ng-repeat etc… which makes AngularJs very powerful, building directive is not a complex thing just like controllers and services we can create our own custom directives

directive

It is very often requirement that displaying user information on multi places on a website, when it comes to AngularJS implementation the best approach for this is create a custom directive and call it on multiple places so that when ever we do any changes at directive level it will automatically reflect on all other places

When browser loads below html , first the standard browser parse the entire html and creates DOM tree, then the Angular HTML compiler looks for any directives which are associated with DOM element, here the “<posts-list>” is a custom directive, once it founds all custom directive definitions then it starts executing directive by invoking link function

There are four ways to invoke directive on the page

  • Element
  • Attribute
  • Comment
  • Class

The element will invoke when we call directive from HTML page like below

The Attribute invoke when we call directive from HTML element as a attribute

The class invoke when we assign directive to HTML element class attribute

The comments invokes when we call directive as a comment

Building Custom Posts Directive :

The below code reads posts from the jsonplaceholder from the controller  using $http module and assign it to the posts scope , in the html section the posts are iterated using ng-repeat directive and invokes custom directive by passing post object, the custom directive call links function and renders html snippet on the page

Did you notice that when we invoke directive the name of directive is not same as defined one , the defined one’s are camelCase but the invoked directive element is not camelCase, we do not need to worry about any thing out here, the Angularjs will translate snakeCase to camelCase automatically when we invoke it

Directive Configuration :

restrict option :

The restrict option specify that how a directive can be invoked on the page, in our posts example we have assigned ‘EA’  to restrict option which means we can invoke this directive either from element or element attribute

There are four ways to invoke directive one the page and the syntax is below

You can specify multiple restrict options to the directive something like this “EA”, if you specify “EA” means you can invoke directive by matching element name or attribute name

 

Leave a Reply

Your email address will not be published. Required fields are marked *