Kevin Carbonaro Kevin Carbonaro - 1 year ago 119
Javascript Question

Converting daterangepicker to angular directive

I am trying to wrap a daterangepicker plugin into an angular directive. Although I managed to make it work by alerting the selected dates in the callback function, I cannot seem to either save the selected dates to the $scope or update the ng-model. I added a comment '// CALLBACK of daterangepicker' so that anyone seeing this can locate it easily in the code below. I hope someone with more experience can shed some light on how this can be achieved.

HTML (calling the directive):

<input id="date-range-picker" class="form-control" type="text"

ng-model="date" time-recorder-date-range-picker />

Angular directive:

module.directive('timeRecorderDateRangePicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
startDate: moment.utc().subtract(7, 'days'),
endDate: moment.utc(),
minDate: '01/01/2014',
maxDate: moment.utc(),
dateLimit: {
days: 365
showDropdowns: false,
showWeekNumbers: true,
timePicker: false,
ranges: {
'Today': [moment.utc(), moment.utc()],
'Yesterday': [moment.utc().subtract(1, 'days'), moment.utc().subtract(1, 'days')],
'Last 7 Days': [moment.utc().subtract(6, 'days'), moment.utc()],
'Last 30 Days': [moment.utc().subtract(29, 'days'), moment.utc()],
'This Month': [moment.utc().startOf('month'), moment.utc().endOf('month')],
'Last Month': [moment.utc().subtract(1, 'month').startOf('month'), moment.utc().subtract(1, 'month').endOf('month')]
opens: 'right',
format: 'MMMM D, YYYY',
separator: ' to ',
buttonClasses: ['btn btn-default'],
locale: {
applyLabel: 'Apply',
cancelLabel: 'Cancel',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
}, function(start, end, label) {
// CALLBACK of daterangepicker
}).prev().on('click', function() { // makes calendar icon click work

Answer Source

You can use dangrossman's bootstrap-daterangepicker in Angularjs project using jqlite, try this


<input type="text" id="daterange" />

Then attach the picker to the element you want to trigger it using jqlite

        timePicker: true,
        timePickerIncrement: 30,
        locale: {
            format: 'MM/DD/YYYY h:mm A'

you can also use events

    angular.element('#daterange').on('apply.daterangepicker', function(ev, picker) {
      //do something, like calling a function
      $scope.doSomething(picker.startDate, picker.endDate);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download