Search code examples
javascriptangularjstwitter-bootstrapdatetimepickerangular-directive

Date-Time-Range directive field is not showing any values


I have created an Date Time Range Directive in AngularJS. I am using dangrossman/bootstrap-daterangepicker plugin for getting the Date Time Range Calendar. The directive is working fine as well as the model value is getting changed but the view is not updating.

      element.data('daterangepicker').setStartDate(val.start); 
      element.data('daterangepicker').setEndDate(val.end); 

Can anyone please tell me some solution for this.

My Directive which I have created is given below

Plunker

script

app.directive('dateTimePicker', function($parse, $compile) {
  return {
    restrict: "E",
    replace: true,
    transclude: false,
    compile: function(element, attrs) {
      var modelAccessor = $parse(attrs.ngModel);

      var html = "<form>" +
        "<div class='form-group'>" +
        "<div class='input-group'>" +
        "<span class='input-group-addon'>" +
        "<i class='fa fa-calendar'></i>" +
        "</span>" +
        "<input type='text' name='reservation' id='reservationtime' class='form-control' value=''/>" +
        "</div>" +
        "</div>" +
        "</form>";

      var newElem = $(html); 

      element.replaceWith(newElem); 

      return function(scope, element, attrs, controller) {

        element.on('apply.daterangepicker', function(ev, picker) 
        {
          var date = {};

          date.start = picker.startDate;
          date.end = picker.endDate;
          scope.$apply(function (scope) {
              modelAccessor.assign(scope, date); 
           });
        });  

        element.daterangepicker({
          timePicker: true,
          timePickerIncrement: 30,
          format: 'MM/DD/YYYY h:mm A'
        });

        scope.$watch(modelAccessor, function(val) 
        {
          console.log(val);
          if(!_.isUndefined(val))
          {
            element.data('daterangepicker').setStartDate(val.start); 
            element.data('daterangepicker').setEndDate(val.end); 
          }
        });  

      };

    }
  };
});

html

  <date-time-picker ng-model="dateTimeRange"></date-time-picker>

Solution

  • updateInputText: function() {
                if (this.element.is('input') && !this.singleDatePicker) {
                    this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
                } else if (this.element.is('input')) {
                    this.element.val(this.endDate.format(this.format));
                }
            }
    

    This code snippet from daterangepicker.js is responsible for updating the view.

    In the dateTimePicker directive, the root element of the template i.e, form element is converted to daterange widget using element.daterangepicker where as input element inside the template should be converted.

    element.find('input').daterangepicker({}) worked for me.