How to wrap the datetimepicker js into AngularJS directive

前端 未结 7 2190
陌清茗
陌清茗 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:05

    I really struggled long with Eonasdan datetime picker. Most of the solutions published on the web work ok or not-so ok.

    In the end I merged some of the solutions I have found online. I wrapped it in a working plunker: http://plnkr.co/n8L8UZ

    The directive works using ng-model in moment format, what is more it allows two functions to be passed: onDateChangeFunction and onDateClickFunction which are called respectively.

    Happy using!


    The directive source code:

    angular
        .module('plunker')
        .directive('datetimepicker', [
          '$timeout',
          function($timeout) {
            return {
              require: '?ngModel',
              restrict: 'EA',
              scope: {
                datetimepickerOptions: '@',
                onDateChangeFunction: '&',
                onDateClickFunction: '&'
              },
              link: function($scope, $element, $attrs, controller) {
                $element.on('dp.change', function() {
                  $timeout(function() {
                    var dtp = $element.data('DateTimePicker');
                    controller.$setViewValue(dtp.date());
                    $scope.onDateChangeFunction();
                  });
                });
    
                $element.on('click', function() {
                  $scope.onDateClickFunction();
                });
    
                controller.$render = function() {
                  if (!!controller && !!controller.$viewValue) {
                    var result = controller.$viewValue;
                    $element.data('DateTimePicker').date(result);
                  }
                };
    
                $element.datetimepicker($scope.$eval($attrs.datetimepickerOptions));
              }
            };
          }
        ]);
    

提交回复
热议问题