Skip to content

Instantly share code, notes, and snippets.

@eugenekgn
Last active August 27, 2024 20:09
Show Gist options
  • Select an option

  • Save eugenekgn/f00c4d764430642dca4b to your computer and use it in GitHub Desktop.

Select an option

Save eugenekgn/f00c4d764430642dca4b to your computer and use it in GitHub Desktop.
(function () {
var dateTimeController = function ($scope, $rootScope) {
$scope.vm = {
message: "Bootstrap DateTimePicker Directive",
dateTime: {}
};
$scope.$watch('change', function(){
console.log($scope.vm.dateTime);
});
/*
$scope.$on('emit:dateTimePicker', function (e, value) {
$scope.vm.dateTime = value.dateTime;
console.log(value);
})
*/
};
var dateTimePicker = function ($rootScope) {
return {
require: '?ngModel',
restrict: 'AE',
scope: {
pick12HourFormat: '@',
language: '@',
useCurrent: '@',
location: '@'
},
link: function (scope, elem, attrs) {
elem.datetimepicker({
pick12HourFormat: scope.pick12HourFormat,
language: scope.language,
useCurrent: scope.useCurrent
})
//Local event change
elem.on('blur', function () {
console.info('this', this);
console.info('scope', scope);
console.info('attrs', attrs);
/*// returns moments.js format object
scope.dateTime = new Date(elem.data("DateTimePicker").getDate().format());
// Global change propagation
$rootScope.$broadcast("emit:dateTimePicker", {
location: scope.location,
action: 'changed',
dateTime: scope.dateTime,
example: scope.useCurrent
});
scope.$apply();*/
})
}
};
}
angular.module('dateTimeSandbox', []).run(['$rootScope', function ($rootScope) {
}]).controller('dateTimeController', ['$scope', '$http', dateTimeController
]).directive('dateTimePicker', dateTimePicker);
})();
<html ng-app="dateTimeSandbox">
<head>
<meta charset='utf-8'/>
<title>DatePicker Directive</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet"
href="http://eonasdan.github.io/bootstrap-datetimepicker/content/bootstrap-datetimepicker.css">
</head>
<body>
<div class="container" ng-controller="dateTimeController">
<div class="row">
<div class='col-sm-6'>
<h1> {{vm.message}}</h1>
<div class="form-group">
</div>
<label class="label label-info">DateTimePicker</label>
<br/>
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<br/>
<label class="label label-info">DateTimePicker (Angular Directive)</label>
<br/>
<input type="text"
class="form-control"
ng-model="vm.dateTime"
data-date-time-picker
data-language="{{ru}}"
data-pick12HourFormat="false"
data-use-current="{{false}}"
data-location="{{testProject}}"
/>
<br/>
<pre>{{vm|json}}</pre>
</div>
</div>
</div>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="node_modules/moment/min/moment.min.js"></script>
<script type="text/javascript" src="build\js\bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="angularjs/angular.js"></script>
<script type="text/javascript" src="js/datetimepickerDirective.js"></script>
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({
language: 'ru',
useCurrent: false
});
});
</script>
</body>
</html>
@edgar0011

Copy link
Copy Markdown

got error "option language is not recognized", not working

@metasean

metasean commented Mar 1, 2015

Copy link
Copy Markdown

@eugenekgn - I think @FraGoTe is asking about having multiple datetime pickers on a single page. For example scheduling an activity with a "start" date and time picker and a "end" date and time picker.

I'm actually really interested in seeing a working Plunker version (or other online code system: http://jsbin.com/ , http://jsfiddle.net/ , http://codepen.io/ , etc). So I'm hopeful that you can help @talktoanil's get that Plunker up and running.

@talktoanil

Copy link
Copy Markdown

no update om my query ?

@diosney

diosney commented Mar 16, 2015

Copy link
Copy Markdown

Hi!

I made a wrapper around the datetimepicker plugin and published it via bower.

You can install it by issuing: bower install angular bootstrap datetimepicker.

The official repo is in https://github.com/diosney/angular-bootstrap-datetimepicker-directive, there you will find the README and a 100% working example.html file.

It supports every single option.

If you findout any problem just file an issue.

@Eonasdan Fill free if you want to post a reference in the Installing section.

@diosney

diosney commented Mar 16, 2015

Copy link
Copy Markdown

@FraGoTe With the directive I made you can pass the specific options you want to any datetimepicker instance in the page, just see the example.html file.

@edgar0011 That can be caused due the fact that the language option is hardcoded in the directive definition and not being passed to the directive via HTML.

@talktoanil Sadly plunkr doesn't work for me, maybe you can set up a jsfiddle?

@nazirsj

nazirsj commented Apr 8, 2015

Copy link
Copy Markdown

I have the tried sample code but I am getting an error in the directive.

TypeError: undefined is not a function - it's not finding the datetimepicker

elem.datetimepicker();

Any ideas?

I tried the sample from @diosney but I get the same error in the directive.

@pascalwinter

Copy link
Copy Markdown

@diosney, I have found several problems with your wrapper directive. Firstly, it does not set the date of the calendar to the value of your model. Therefore, when you trigger the datepicker it does not display the correct month or day, but the current month and day.

Also your approach does not allow you to trigger the datepicker on button click, rather it is triggered by focusing the input box.

@mwadams

mwadams commented Apr 23, 2015

Copy link
Copy Markdown

I've forked this here, with an update of @diosney 's code that does two-way model binding. You can apply it to the outer input-group to get the click behavior.

@diosney

diosney commented Apr 28, 2015

Copy link
Copy Markdown

@pascal0828 Thanks for reporting the issue, I already fixed them using @mwadams solution (thanks!!!)

@diosney

diosney commented Apr 28, 2015

Copy link
Copy Markdown

@nazirsj It seems to me that you have to load the jQuery plugin into the page, something like:

<script src="vendors/bower_components/moment/min/moment.min.js"></script>
<script src="vendors/bower_components/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"></script>

@naczu

naczu commented Jun 24, 2015

Copy link
Copy Markdown

this works fine for me.

app.directive('dDatepicker', function($timeout, $parse) {
        return {
            link: function($scope, element, $attrs) {
                return $timeout(function() {
                    var ngModelGetter = $parse($attrs['ngModel']);

                    return $(element).datetimepicker(
                        {
                            minDate:moment().add(1, 'd').toDate(),
                            sideBySide:true,
                            allowInputToggle:true,
                            locale:"tr",
                            useCurrent:false,
                            defaultDate:moment().add(1, 'd').add(1,'h'),
                            icons:{
                                time: 'icon-back-in-time',
                                date: 'icon-calendar-outlilne',
                                up: 'icon-up-open-big',
                                down: 'icon-down-open-big',
                                previous: 'icon-left-open-big',
                                next: 'icon-right-open-big',
                                today: 'icon-bullseye',
                                clear: 'icon-cancel'
                            }
                        }
                    ).on('dp.change', function(event) {
                            $scope.$apply(function() {
                                return ngModelGetter.assign($scope, event.target.value);
                            });
                    });
                });
            }
        };
    });

@cloidjgreen

Copy link
Copy Markdown

I found the language element to not be working properly. Removed it in all locations of HTML and js code and it works.

Will keep digging as I need locale aware code.

This is not a complaint, just a comment.

Nice work

Thanks

And I just bore down into moment and found that 'en' is not a language, 'en-gb' will work so the code implemented flawlessly

@bramcordie

Copy link
Copy Markdown

@cloidjgreen It's probably a version thing but I had to use locale instead of language to translate the UI.

I also need the dutch (nl) translations and managed to include them using grunt and wiredep by overwriting the main files in my Grunt-file like so:

wiredep: {
  options: {
    'overrides': {
      'moment': {
        'main': [
          'moment.js',
          'locale/nl.js'
        ]
      }
    }
  }
}

@ralvarezalonso

Copy link
Copy Markdown

@diosney thanks a lot for the wrapper!
How could I make the datepicker appear not when the user clicks on the input, but when clicks on the calendar icon?

UPDATED: I managed to do it following mwadams's solution. Thank you to both of you!

@atais

atais commented Oct 16, 2015

Copy link
Copy Markdown

Out of all of above I recommend @mwadams solution.

@SandeepThomas

Copy link
Copy Markdown

How to make the datepicker appear on clicking calendar icon by using the official directive?

@atais

atais commented Nov 10, 2015

Copy link
Copy Markdown

I combined @mwadams and @diosney solution into this nice plnker :) happy using
http://plnkr.co/n8L8UZ

Since the previous project has been abandoned I have created a fork and pushed all the changes there.
https://github.com/atais/angular-eonasdan-datetimepicker

@JiriMachacek

Copy link
Copy Markdown

@atais plunker not found :(

@JiriMachacek

Copy link
Copy Markdown

@atais now it works. THX

@dotku

dotku commented Dec 15, 2015

Copy link
Copy Markdown

useCurrent() expects a string parameter of year, month, day, hour, minute

@dodonnell12

Copy link
Copy Markdown

@atais

Using your code doesn't allow the datetimepicker sideBySide: true attribute to work now. Any suggestions?

$(function () {
        $('#datetimepicker1').datetimepicker({
            sideBySide: true
        });
    });

Figured it out. Add sideBySide: true into the vm.options. Like this.
vm.options = '{format:"DD.MM.YYYY HH:mm", sideBySide: true}'

Also if you need the AM PM formatting remove the format option completely. Like this.
vm.options = '{sideBySide: true}

@leguin

leguin commented Feb 6, 2016

Copy link
Copy Markdown

@atais
Thanks, it works great.
Small issue, maybe you can suggest how to solve it.
When I am trying to navigate with the left and right keys inside of input and datetimepicker is closed, it doesn't always work as expected.

You have repro in your plunkr: http://plnkr.co/kNqCuQ

Any suggestion ?

@atais

atais commented Feb 9, 2016

Copy link
Copy Markdown

@leguin it because left-right arrow is also captured by the datepicker to navigate over the calendar. It is not a wrapper's, but library's fault.

@penndai

penndai commented Jun 17, 2016

Copy link
Copy Markdown

Do you support angular 2? It is hard to find any adaptable time picker for the new angular 2 online.

@GBurlakova

GBurlakova commented Jul 8, 2016

Copy link
Copy Markdown

Yes, do you support angular2? I am currently trying to integrate the datetimepicker with an angular2 application but I get an error as follows TypeError: Cannot read property 'addClass' of undefined

@gitsubham

gitsubham commented Jul 13, 2016

Copy link
Copy Markdown

how to require it as npm package ?
we are using eonasdan-bootstrap-datetimepicker-npm. and after that, we are requiring it as follows

require ('eonasdan-bootstrap-datetimepicker-npm')

also we have tried

require ('bootstrap-datetimepicker')

What are we doing incorrectly ?

@crohit92

crohit92 commented Jan 23, 2017

Copy link
Copy Markdown

The directive does not work correctly, it does not perform two way data binding, to fix the issue i modified it a bit and added another scope model in the directive, see the attached image

image

I have added ngModel in the directive to receive a model, and it is updates whenever the value in the directive updates, i.e. in the on blur event.

@shamoh19

Copy link
Copy Markdown

any update on how to integrate with Angular2?

@nalex-macaroni

Copy link
Copy Markdown

This worked pretty nicely out of the box - My only issue is that I can't seem to connect two together to get a date range. I tried to get the minDate option to react to the first picker's model, but it didn't like that...tried $( "#picker2ID" ).minDate() - doesn't work..etc.. Any ideas how this can work? Thanks!

@eprislac

eprislac commented Sep 20, 2017

Copy link
Copy Markdown

I switched things up a bit and made a component instead of a directive wrapper:
https://gist.github.com/eprislac/9b1f7d9f172bb3447be848a36a27af7d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment