Click here to Skip to main content
15,897,718 members
Articles / Web Development / HTML
Tip/Trick

Datepicker directive using AngularJS and Bootstrap

Rate me:
Please Sign up or sign in to vote.
4.71/5 (10 votes)
6 Aug 2014CPOL3 min read 104.3K   3.4K   12   4
This is simple creating datepicker directive using AngularJs and Bootstrap

Introduction

Directive is very exciting component when you develop web application with AngularJS. I have just research a lot of topic in the internet and try to complete simple datepicker directive using with Bootstrap latest version v3.2.0. With component you can use very easy and customize what you want to do. I referenced Angular Datepicker, but it so complicated control. Write the code with Datepicker help me to understand how to write directive in angular.

Background

With the sample project, It is the basic ideas about building application using RequireJS, Angular Routing, Binding. This a simple to understand create directive, controller, service, loading dependency in AngularJS. To understand the source code, you should basic knowledge about AngularJS, Bootstrap, HTML, CSS.

Using the code

The source code step by step create simple page with only directive for the testing. The tree of project like this.

It include AngularJS libararies, Bootstrap, and our datepicker directive. The direcuve base on bootstrap datepicker libray. The basic flow of application: inject RequireJS in index.html to load main.js--> app.js. In main.js, I load directive and Index controller. Before going deeply the soure code. I explain the basic about isolated scope in directive.

While creating directives, AngularJS allows you to create an isolated scope with some custom bindings to the parent scope. There are 3 types of binding options which are defined as prefixes in the scope property. The prefix is followed by the attribute name of HTML element. These types are as follows

Text Binding (Prefix: @) It like variable
One-way Binding (Prefix: &) It like function
Two-way Binding (Prefix: =) It like value

In this project I used 2 way binding. I put direcive in the index.html and pass value 2 way binding to directive. I will explain more detail in the source below.

The first I create directive with type of attribute.

JavaScript
define(['app', 'directive/datepickerCtrl'], function (app) {
    app.directive('datepicker', function () {
        return {
            restrict: 'A',
            controller: 'datepickerCtrl',
            controllerAs: 'dp',
            templateUrl: 'app/directive/datepicker.html',
            scope: {
                'value': '='
            },
            link: function (scope) {
               
            }
        };
    });
});

In the directive, I inject datepicketCtrl to handle the scope. You can handle change value of scope variable in the controller or in the direct link: function.

JavaScript
define(['app'], function (app) {
    app.controller('datepickerCtrl', function ($scope) {
        var self = this;
        $('.date').datepicker({ autoclose: true, todayHighlight: true });
        $scope.$watch('value', function (oldVal, newVal) {
                        console.log("Value: "+ $scope.value);
        });
    } );
});

In the controller, I init for datepicker trigger libary javascript, some option params.

JavaScript
$('.date').datepicker({ autoclose: true, todayHighlight: true });

In the directive, I link to datepicker template html. In the template I use ng-model for 2 way binding. I pass 

variable named "value" from parent controller to directive.

HTML
<div class="input-group date" data-date-format="dd-mm-yyyy" >
    <input type="text" ng-class={inputError:dp.validDate==false} class="form-control input-sm" ng-model="value" />
    <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>

I put input class inputError to check the input date for customize. You can remove it.

After creating directive, I load it using RequireJS in the main file

JavaScript
require(
    [
        'app',
        'directive/datepicker',
        'indexCtrl'

    ],
    function (app) {
        app.config([
        .....
          
        }
    ]);
        angular.bootstrap(document, ['testApp']);
    });

And put it in the index.html file

HTML
<div ng-controller="indexCtrl">
    <div class="col-xs-2" datepicker value="birthday">
</div>

It is wrapped by index controller. You can pass varaibe from index controller to directive throught value atribute. The finally result on the browser like...

History

This is the first version of project.

Here is my update version with format update date time UTC using moment.js

Points of Interest

The datepicker libary I reference from http://bootstrap-datepicker.readthedocs.org/en/release/  so interest. With the new version, you dont care about corect format date time. For more detail about API you can reference the home page.

I want to say thank Stefan Petre, Andrew Rowls + who contributors datepicker bootstrap more completion. Enjoy your coding.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect OSM Solution Vietnam Ltd. Co.
Vietnam Vietnam
We are working in Web Application with SPA, MVC domain. Beside we are master in Management Information Systems, how to use IS to improve decision making and knowledge sharing in open learning organization.

Comments and Discussions

 
QuestionDate picker Pin
Member 120430458-Oct-15 1:54
Member 120430458-Oct-15 1:54 
AnswerRe: Date picker Pin
Chinh Vo Wili8-Oct-15 4:59
professionalChinh Vo Wili8-Oct-15 4:59 
Questionask Pin
Member 1063553723-Aug-14 18:26
Member 1063553723-Aug-14 18:26 
AnswerRe: ask Pin
Chinh Vo Wili23-Aug-14 19:29
professionalChinh Vo Wili23-Aug-14 19:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.