Custom Directives in AngularJS with example and demo

Create angularjs custom directive Create angularjs two way binding custom directive Custom directive in angularjs Angularjs directive basics Learn angularjs custom directive with example Angularjs custom directive demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are the directives which is created by experts for us to speed up our daily life coding. In this article we will try to learn some basics of angularjs directives.

By default all the directives runs under parent scope, let's say you want to create directive to concatenate first name and last name then

angular.module('myApp')
 .directive('myFullname', function () {
    return {
        template: 'Full Name: {{customer.firstName}} {{customer.lastName}}'
    };
});

Now if I am using in my one of view like this:

<div ng-controller="customerController">
  <div my-fullname></div>
  .......................
  .......................  
</div>
  • In this case it will read the customer data on the scope
  • Read firstName and lastName in customer object and concatenate it.
  • Same thing can be achieve by using html template so not very impressive
  • It cannot be used with any other object say user on the scope because it always try to read from customer
  • What if we want to pass the first name and last name as a parameter, then we need an isolate scope directive.

What is Isolate Scope?

Directive will be dependent in it's own scope and not to another scope out side of the directive. Problem in the above scenario is that, every time we need to use the directive, we need a separate controller from where data will be taken and rendered, but easily we can create directive which will run in isolate scope, let's create one by using the above example:

angular.module('myApp')
 .directive('myFullname', function () {
    return {
        scope: {
            firstName: '@',
            lastName: '@'
        },
        template: 'Full Name: {{firstName}} {{lastName}}'
    };
});

Note we declared two scope variables inside the directive and expect values for it, how can it be used, let's try it

<div my-fullname 
    first-name="{{user.firstName}}" 
    last-name="Hard coded value" >
</div>
  • In this case, we are passing two value
  • One from the user first name and
  • Other hard coded
  • Good thing is that if user first name changes, directive value will automatically changed, only one way
  • But if you will try to change the value in directive, it will not reflect to the user
  • It can be used only if need to show the data

Things to note:

  • function() does not have any parameter
  • firstName is used like first-name and lastName as last-name in html to accept the data
  • If the variable is like customerAddressCityName then it will be used like customer-address-city-name
  • Means every capital letter will be used in lower case preceding with hyphen (-)

Question: Can we create a two way binding directive, answer is yes, which we are going to create in our next example.

Let's say we have a big page like this:

<form class="form-horizontal">

    <div class="form-group">
        <label for="FirstName" class="col-sm-3 control-label">First Name</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="FirstName" ng-model="FirstName">
        </div>
    </div>

    <div class="form-group">
        <label for="LastName" class="col-sm-3 control-label">Last Name</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="LastName" ng-model="LastName">
        </div>
    </div>

    <div class="form-group">
        <label for="Address" class="col-sm-3 control-label">Address</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="Address" ng-model="Address">
        </div>
    </div>
    -----------------------------
    -----------------------------
</form>

If I want to create a directive which can take care about the entire row with label, property binding and can be saved easily with current scope, in all the above examples we used the in-line template, in this example we will create a separate template file html file and use templateUrl in place of template:

// Directive code
app.directive('textBox', function () {
    return {
        scope: {
            label: '@label',
            value: '@value',
            property: '='
        },
        restrict: 'E',
        replace: true,
        templateUrl: 'app/views/textbox.html'
    };
});

// textbox.html file code
<div class="form-group">
    <label for="{{value}}" class="col-sm-3 control-label">{{label}}</label>
    <div class="col-sm-6">
        <input type="text" class="form-control" id="{{value}}" ng-model="property[value]" />
    </div>
</div>

Before using this code in any page, which is not hard, we need to learn what we are doing in our directive, so let's dive in it

  • We create scope inside the directive as earlier (isolate scope)
  • label: simply accepting label text as string
  • value: it will accept the property name, say firstName from user object
  • property: note the = sign, it used to do the two way binding, it will accept scope object, say user
  • restrict: 'E': can be used an element, 'EA': can be used as element as well as attribute etc.
  • In html I used for="{{value}}" and id="{{value}}" so when user click on label it will go to that text box
  • Note how we are bind the property and value ng-model="property[value]"

Now see the above big HTML will be converted in this small piece of code:

<form class="form-horizontal">
    <text-box label="First Name" property='customer' value="firstName"></text-box>
    <text-box label="Last Name" property='customer' value="lastName"></text-box>
    <text-box label="Address" property='customer' value="address"></text-box>
    -----------------------------
    -----------------------------
</form>

Check the live demo on plunker

How the handle the events in directive, I will add latter on.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • angularjs
  • directive
By Ali Adravi On 29 Jul, 15  Viewed: 3,032

Other blogs you may like

Angularjs powerful paging on table and searching with delay and demo

Paging on table is the basic requirement and most of us look for some grid so it can provide the complete feature of paging and sorting but in Angularjs it is so easy that anyone can achieve it by writing some code. I checked and found most of the available code give the paging feature in for 1 to... By Ali Adravi   On 14 Aug 2015  Viewed: 10,099

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 39,381

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 15,001

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 26,007

Angularjs Progress bar directive for entire application

Progress bar for Angularjs application by using directives is simple and real easy. I was googling and could not found any directive way, if you will check most of the people says before call the http method open the progress bas and close once you get the result or get any error. Do you think it... By Ali Adravi   On 24 Jul 2015  Viewed: 11,673