Monday, March 14, 2016

Bootstrap DateTime Picker with AngularJS Directive



Problem: I wanted to use the eonasdan’s Boostrap Datetime picker in my Share Point hosted App.

Solution: I have wrapped the eonasdan’s Bootstrap DateTime picker by creating a directive in my controller.



AngularMain.controller("MyController", function() {})
    .directive('bootdatepicker', ['$timeout', renderBootStrapDatePicker]);

function renderBootStrapDatePicker($timeout) {
    var format = "DD/MM/YYYY";
    return {
        restrict: 'EA',
        require: 'ngModel',
        link: function(scope, element, attributes, ngModelCtrl) {
            // Initialize the DateTime Picker with a format
            element.datetimepicker({
                format: format
                    /*,
                                                defaultDate: function () { return moment().format(format); }*/
            });

            // Get the DateTime Picker
            var datePicker = element.data('DateTimePicker');

            element.on('dp.change', function() {
                $timeout(function() {

                    var selectedDate = moment(datePicker.date()).format("DD/MM/YYYY");
                    ngModelCtrl.$setViewValue(selectedDate);
                });
            });

        }
    };

The following is 'RenderBootStrap' directive is bound to the view.
I hope, this may help someone.. :)