Tutorial 15: Custom Directives in AngularJS

In AngularJS by Administrator22 Comments

This is angularjs custom directive tutorial. Lets see, how to make custom directives in angularjs? We will be making use of our existing guitar angularjs app which we have been working in Tutorial 14: Form Validation in AngularJS. You can download previous tutorial app here. Ok lets start, with angularjs directive. As we know that:

Angularjs Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s html compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children. For example, The ng-app attribute is a directive, so is ng-controller and all of the ng-, ng:, ng_, x-ng-bind, data-ng-bind prefixed attributes.

So custom directives in angularJS is your own directive with their own core functions that runs when the DOM is compiled by the compiler. Thats may be difficult. Suppose, if we want to reuse specific lines of code in different pages of our application without code duplication then we simply put that specific piece of code in a separate file and call that code using a custom directive instead of writing it over and over again. This way code is better to understand. There are four types of custom directives:

  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives

Before implementing it in our existing angular app lets see how custom directives looks like:

Element directives

In the html file write following element tag. This tag will hold code snippet. When we want to use specific code we simply write such tags to include that code.

Then in the JS file, write following lines to make above angularJS custom directive work.

Code Explanation:

Like app.controller we defined app.directive then defined guitarReview which is the name of element tag that is being used in html but have you noticed that guitar-review is different from guitarReviews? This is because guitar-reviews’s hypen is converted into camel case so it becomes guitarReviews in js file. Next is an anonymous function which is returning something. restrict: ‘E’ says that we are defining a custom Element directive and templateUrl is pointing to code snippet file that has to be included.

Attribute directives

In the html file write following attribute inside html tag. This tag will hold code snippet. When we want to use specific code we simply write such tags to include that code.

Then in the JS file, write following lines to make above angularJS custom directive work.

Note: AngularJS recommends that you leave simple css and normal comments instead of custom directives for css and comments.

Lets implement custom directives in our angularJS app. You can download project files here. I want to put reviews section code in a separate file and then gonna assign an element to that code snippet and use it in details.html page.

First

In partials folder create a new folder named as cDirectives to hold custom directives. Then inside cDirectives create a new file named as reviews.html that will hold reviews of user. So your folder hierarchy must look like this:

AngularJS Project Download

Second

Goto details.html file and cut the review area and add <user-reviews></user-reviews> tag like this:AngularJS Sample Code

Third

Paste the code you cut from details.html page to reviews.html page like this:

Fourth

Now is the time to add behavior to user-reviews element tag. Lets do it in controllers.js file like this (Goto end and add following code):

 Code Explanation:

Our <user-reviews> directive name here is userReviews in camel case and hyphen is gone. Next we are saying that restrict that directive to element E and when it is called load the file in templateURL.

We just made a custom element directive. Although, you see no change in application but now our code is well managed than before. Can you make custom element directives for description and specifications? Do it yourself.

Interesting part: you can add styles to user-reviews via css like the way you assign style to a div.

Download Project files

Hope you like it. Please share my work.

Previous-Chapter-Button

//

  • Manoj

    good one keep it up !

    • Hafiz Faraz Mukhtar

      Thanks

      • Manoj

        sir do you have any reference for middleware tutorial ?

        • Hafiz Faraz Mukhtar

          not yet

          • Manoj

            ok

          • Manoj

            is this tutorial over now?

          • Hafiz Faraz Mukhtar

            probably yes.. i m working on a project these days so hard for me to write new articles. will resume after mid of august.

          • Manoj

            ok till then bye………………

          • Manoj

            sir do you have question answer related to angular for interview preparation?

          • Hafiz Faraz Mukhtar

            Yes, tomorrow I will try to write an article on AngularJS interview. Thanks for asking.

  • moe yousef

    hello hafiz, did you receive my email with a zip file?

    thanks,
    moe yousef

    • Hafiz Faraz Mukhtar

      yeah i received your email.

  • I love being able to find posts regarding things
    like this… keep me updated. Thanks for the useful article about Angular JS.

  • charan

    hi i am new to angularjs,
    this is simple question

    in js…
    ————–
    app.directive(‘guitarReviews’, function() {
    return {
    restrict : ‘A’, // used A because of attribute
    templateUrl : ‘custom-directives/reviews.html’
    };
    });
    in html…
    ———-

    while creating directive we are given name as ‘guitarReviews’ and while in html we are
    writing ‘guitar-reviews’ what is nesesity of the ‘-‘,where i need to give the ‘-‘symbol.
    if i give more than once and another place i am not getting output,can u please clarify.

    thanks.

    • this is how we do it in angularJS .. we declare like: camelCase and call like camel-case .. in simple words its a rule as far as i know.

    • Hb

      … —– is not applicable. guitar-reviews is not a directive. A directive usually comes with ng-, ng_ or simply ng…. eg: ng-click = ng_click = ngclick; But Angular recommends ng-click format;

  • Mithun H.A

    Great tutorials Hafiz, Well can you post an simple project with database connectivity. So that it will be like a real world environment… And what is angularui and angular-bootstrap?

  • tommy

    Thanks a lot for the tutorials. Really great tutorials on Angularjs. Look forward for more tutorials from you. Cheer =D