How to wrap the datetimepicker js into AngularJS directive

前端 未结 7 2193
陌清茗
陌清茗 2020-12-15 01:59

I have spent sometime on researching the existing datetime directives of angularjs.

Both ngularUI and AngularStrap do not provide a datetimepicker as I needed. Of co

7条回答
  •  忘掉有多难
    2020-12-15 02:16

    To complete cdmckay's solution so the datetime picker widget is correctly initialized with the ng-model's value, I've added a listener on dp.show event. So, my solution is :

    'use strict';
    
    angular.module('frontStreetApp.directives', [])
      .directive('psDatetimePicker', function (moment) {
          var format = 'MM/DD/YYYY hh:mm A';
    
          return {
              restrict: 'A',
              require: 'ngModel',
              link: function (scope, element, attributes, ctrl) {
                  element.datetimepicker({
                      format: format
                  });
                  var picker = element.data("DateTimePicker");
    
                  ctrl.$formatters.push(function (value) {
                      var date = moment(value);
                      if (date.isValid()) {
                          return date.format(format);
                      }
                      return '';
                  });
    
                  /**
                  * Update datetime picker's value from ng-model when opening the datetime picker's dropdown
                  */
                  element.on('dp.show', function() {
                      picker.setDate(ctrl.$viewValue);
                  });
    
                  /**
                  * Update ng-model when  datetime picker's value changes
                  */
                  element.on('change', function (event) {
                      scope.$apply(function () {
                          var date = picker.getDate();
                          ctrl.$setViewValue(date);
                      });
                  });
              }
          };
      });
    

提交回复
热议问题