top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create a AngularJS custom datepicker directive?

+3 votes
1,265 views
How to create a AngularJS custom datepicker directive?
posted Jun 18, 2015 by Khusboo

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

First we create a datepicker directory with the attributes.
Then create a HTML file named Date.html and the following code in that file:

<div>  
    <input type="text" class="form-control" style="width:{{DateParam.width}};" placeholder="{{DateParam.placeHolder}}"  
           ng-model="DateParam.selectedDate" id="{{TextControlID}}" ng-disabled="DateParam.Disabled" ng-click="open($event)"  
           ng-model-options="{debounce:1000}" ng-change="fnChangeDate();">  

    <input type="text" class="form-control" datepicker-popup="{{DateParam.dateFormat}}" is-open="opened" min-date="DateParam.minDate" max-date="DateParam.maxDate"  
           datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close"  
           style="width:{{DateParam.width}}; visibility:hidden; height:0; padding:0;" ng-model="CalDate" show-weeks="DateParam.showWeeks"  
           show-button-bar="DateParam.showButtonBar" year-range="DateParam.yearRange" datepicker-mode="DateParam.datepickerMode"  
           starting-day="1" />  
    <span class="input-group-btn" style="visibility:{{hidden}}; ">  
        <button type="button" id="{{ButtonControlID}}" class="btn btn-default" ng-click="open($event)" ng-disabled="DateParam.Disabled">  
            <i class="glyphicon glyphicon-calendar"></i>  
        </button>  
    </span>  
</div>  

Now we need to define the Angular app as in the following:

var CustomCtrlApp = angular.module('CustomCtrlApp', ['ui.bootstrap']);   

Now, in the script folder, add a JavaScript file named Date.js that is basically the controller file of the datepicker directory.
In the JavaScript file, add the following code:

CustomCtrlApp.directive("ngDate", ['$filter', function () {  
    this;  
    return {  
        restrict: "EA",  
        scope: {  
            DateSetup: '=dateSetup'  
        },  
        templateUrl: '../HTMLTemplate/Date.html',  
        controller: function ($scope, $element, $attrs, $filter) {  
            $scope.initializeAttribute = function () {  
                $scope.DateChange = false;  
                $scope.DateParam = $scope.DateSetup;  
                $scope.TextControlID = ($scope.DateParam.Id == undefined ? 'dtp1' : $scope.DateParam.Id);  
                $scope.ButtonControlID = ($scope.DateParam.Id == undefined ? 'btn1' : $scope.DateParam.Id);  

                if ($scope.DateParam.dateFormat == undefined) {  
                    $scope.DateParam.dateFormat = 'shortDate';  
                }  

                if ($scope.DateParam.showWeeks == undefined) {  
                    $scope.DateParam.showWeeks = false;  
                }  

                if ($scope.DateParam.showButtonBar == undefined) {  
                    $scope.DateParam.showButtonBar = false;  
                }  

                if ($scope.DateParam.showCalendarIcon == undefined) {  
                    $scope.DateParam.showCalendarIcon = false;  
                }  

                $scope.hidden = $scope.DateParam.showCalendarIcon == true ? 'visible' : 'hidden';  

                if ($scope.DateParam.selectedDate == undefined) {  
                    $scope.CalDate = $scope.FormatDate(new Date());  
                    $scope.DateParam.selectedDate = '';  
                }  
                else {  
                    $scope.CalDate = $scope.FormatDate($scope.DateParam.selectedDate);  
                    $scope.DateParam.selectedDate = $scope.FormatDate($scope.DateParam.selectedDate);  
                }  

                if ($scope.DateParam.width == undefined) {  
                    $scope.DateParam.width = '80%';  
                }  

                if ($scope.DateParam.minDate == undefined) {  
                    $scope.DateParam.minDate = null;  
                }  

                if ($scope.DateParam.maxDate == undefined) {  
                    $scope.DateParam.maxDate = null;  
                }  

                if ($scope.DateParam.yearRange == undefined) {  
                    $scope.DateParam.yearRange = 20;  
                }  

                if ($scope.DateParam.datepickerMode == undefined) {  
                    $scope.DateParam.datepickerMode = 'day';  
                }  

            }  

            $scope.initializeMethod = function () {  
                $scope.DateParam.method = {  
                    setEnabled: function (args) {  
                        $scope.DateParam.Disabled = !args;  
                    },  
                    setMinDate: function (minDate) {  
                        $scope.DateParam.minDate = minDate;  
                    },  
                    setMaxDate: function (maxDate) {  
                        $scope.DateParam.maxDate = maxDate;  
                    },  
                    getMinDate: function () {  
                        return $scope.DateParam.minDate;  
                    },  
                    getMaxDate: function () {  
                        return $scope.DateParam.maxDate;  
                    },  
                    setSelectedDate: function (selDate) {  
                        $scope.CalDate = $scope.FormatDate(selDate);  
                        $scope.DateParam.selectedDate = $scope.FormatDate(selDate);  
                    },  
                    getSelectedDate: function () {  
                        return $scope.CalDate;  
                    },  
                    clearSelection: function () {  
                        $scope.clear();  
                    }  
                };  
            }  

            $scope.clear = function () {  
                $scope.CalDate = null;  
                $scope.DateParam.selectedDate = null;  
            };  

            $scope.open = function ($event) {  
                $event.preventDefault();  
                $event.stopPropagation();  
                $scope.opened = true;  
            };  

            $scope.$watch('CalDate', function () {  
                if ($scope.opened) {  
                    $scope.opened = false;  
                    $scope.DateParam.selectedDate = $scope.FormatDate($scope.CalDate);  
                    $scope.DateParam.events.onDateChanged(new Date($scope.CalDate));  
                }  
            });  

            $scope.$watch('DateParam.selectedDate', function () {  
                if ($scope.DateChange) {  
                    $scope.opened = true;  
                    $scope.CalDate = $scope.DateParam.selectedDate;  
                }  
            });  

            $scope.fnChangeDate = function () {  
                $scope.DateChange = true;  
            }  

            $scope.dateOptions = {  
                formatYear: 'yy',  
                startingDay: 1  
            };  

            $scope.FormatDate = function (args) {  
                return $filter('date')(args, $scope.DateParam.dateFormat);  
            }  

            $scope.initializeAttribute();  
            $scope.initializeMethod();  
        }  
    }  
}]);  

In the preceding code, we specify some attribute of the Datepicker control like:

Width
selectedDate
Date Format
Min Date
Max Date
Enabled
Place Holder
Show weeks
Show Button Bar

Also, we need defined the onDateChanged Event that is fired on the target page after date selection.

Also, we need defined some methods of the datepicker control like:

SetEnabled
setMinDate
SetMaxDate
getMinDate
getMaxDate
getSelectedDate
clearSelection

Now add a HTML page in the HTML folder named DateDemo.html and add the following code there:

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <title>Date Demo</title>  
    <script src="../RefScript/angular.min.js"></script>  
    <script src="../RefScript/ui-bootstrap.min.js"></script>  
    <script src="../RefScript/ui-bootstrap-tpls.min.js"></script>  
    <script src="../PageScript/CustomCtrlApp.js"></script>  
    <script src="../DirectiveScript/Date.js"></script>  
    <script src="../PageScript/DateDemo.js"></script>  

    <link href="../RefStyle/bootstrap.min.css" rel="stylesheet" />  

</head>  
<body ng-app="CustomCtrlApp">  
    <div ng-controller="DateDemo">  
        <table width="100%" cellpadding="0" cellspacing="0">  
            <tr>  
                <td style="width:20%;">Select Date </td>  
                <td style="width:20%;">  
                    <ng-date date-setup="DateArgs"></ng-date>  
                </td>  
                <td style="width:50%;">  
                    <input type="button" value="On/Off" ng-click="fnToggle()" />  
                    <input type="button" value="Clear" ng-click="fnClear()" />  

                    <input type="button" value="Set Min Date" ng-click="fnSetMinDate()" />  
                    <input type="button" value="Set Max Date" ng-click="fnSetMaxDate()" />  
                    <input type="button" value="Set Sel Date" ng-click="fnSetSelDate()" />  

                    <input type="button" value="Get Min Date" ng-click="fnGetMinDate()" />  
                    <input type="button" value="Get Max Date" ng-click="fnGetMaxDate()" />  
                    <input type="button" value="Get Sel Date" ng-click="fnGetSelDate()" />  
                </td>  
            </tr>  
            <tr>  
                <td>{{SelectedDate}}</td>  
            </tr>  
        </table>  
    </div>  
</body>  
</html>  

Now define the datedemo controller.
Add another JavaScript file in the script folder named datedemo.js and add the following code:

CustomCtrlApp.controller("DateDemo", ['$scope', '$http', '$filter',  
    function ($scope, $http, $filter) {  
        $scope.Heading1 = "Date Control";  

        $scope.DateArgs = {  
            width: '70%',  
            //selectedDate: new Date(),  
            dateFormat: 'dd/MM/yyyy',  
            //minDate: new Date('2010-04-14'),  
            //maxDate: new Date('2015-07-24'),  
            enabled: true,  
            placeHolder: 'Enter DOB',  
            Id: 'dtpDOB',  
            showWeeks: false,  
            showButtonBar: false,  
            showCalendarIcon: false             
        };  

        $scope.Enable = true;  

        if ($scope.DateArgs.events == undefined) {  
            $scope.DateArgs.events = {};  
        }  

        $scope.DateArgs.events.onDateChanged = function (args) {  
            $scope.SelectedDate = $filter('date')(args, $scope.DateArgs.dateFormat);  
        }  

        $scope.fnToggle = function () {  
            $scope.Enable = !$scope.Enable;  
            $scope.DateArgs.method.setEnabled($scope.Enable);  
        }  

        $scope.fnClear = function () {  
            $scope.DateArgs.method.clearSelection();  
        }  

        $scope.fnGetMinDate = function () {  
            alert($scope.DateArgs.method.getMinDate());  
        }  

        $scope.fnGetMaxDate = function () {  
            alert($scope.DateArgs.method.getMaxDate());  
        }  

        $scope.fnGetSelDate = function () {  
            alert($scope.DateArgs.method.getSelectedDate());  
        }  

        $scope.fnSetMinDate = function () {  
            $scope.DateArgs.method.setMinDate(new Date('2015-01-01'));  
        }  

        $scope.fnSetMaxDate = function () {  
            $scope.DateArgs.method.setMaxDate(new Date('2015-07-31'));  
        }  

        $scope.fnSetSelDate = function () {  
            $scope.DateArgs.method.setSelectedDate(new Date('2015-07-20'));  
        }  
    }]); 
answer Jan 17, 2017 by Pramod Huilgol
...