Search code examples
javascriptangularjstwitter-bootstrapdatetimepicker

Using Bootstrap Datetimepicker DOM object on multiple ng-views in AngularJS app


I am trying to implement two ng-views on an angular app, each of them using a Bootstrap Datetimepicker (https://eonasdan.github.io/bootstrap-datetimepicker/) to select a date. For each view, I have a javascript $(document).ready function (outside of the angular controller, naturally) which configures the Datetimepicker:

$(document).ready(function(){

      $('#datetimepicker12').datetimepicker({
          format: 'YYYY-MM-DD',
          inline: true,
          sideBySide: false,
          minDate: moment()
      });

      var today = $('#datetimepicker12').data("DateTimePicker").getMoment();

      $('#datetimepicker12').on('dp.change', function(e) {
          angular.element(document.getElementById('reservations')).scope().setDate(e.date);
      });


    });

This code configures the DOM div with id #datetimepicker12

When I load the initial view, everything works as expected and the datetimepicker is properly configured and shown. But when I change the ng-view, naturally the $(document).ready is not called again, as it was already called before when first loading the app, and the datetimepicker object that should appear on the new ng-view is not configured once again. As a result, it is not shown any longer. Neither on the second nor first partial. It only appears again if I refresh the page. But then disappears if I change the partial inside the app.

Is there a way around this? I thought a possibility would be to try to call a function outside the angular controller in order for it to be able to configure the object with the .datetimepicker() function. Any suggestions? Thanks!


Solution

  • What actually solved my issue was creating an angular directive for the datetimepicker. With it, I was able to access the JQuery object I wanted and use the datetimepicker formatting functions. I applied the following directive:

    module.directive('datetimepicker', function() {
      return function(scope, element, attrs) {
          element.datetimepicker({
                 format: 'YYYY-MM-DD',
                    inline: true,
                    sideBySide: false,
                    minDate: moment()
           });
    
           var today = $('#datetimepicker12').data("DateTimePicker").getMoment();
    
           element.on('dp.change', function(e) {
                 angular.element(document.getElementById('reservations')).scope().setDate(e.date);
             });
         }
    });
    

    Then on the DOM element, I just added the 'datetimepicker' attribute to the div which held the datetimepicker.