How to wrap the datetimepicker js into AngularJS directive

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

    I had the same issue. Here's what I ended up doing that worked well for me:

    '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 '';
                    });
    
                    element.on('change', function (event) {
                        scope.$apply(function() {
                            var date = picker.getDate();
                            ctrl.$setViewValue(date.valueOf());
                        });
                    });
                }
            };
        });
    

    Here's the HTML:

    <!-- The dueDate field is a UNIX offset of the date -->
    <input type="text"
           ng-model="dueDate"
           ps-datetime-picker
           class="form-control">
    

    You can check out the gists and a bit more information in my blog post.

    0 讨论(0)
提交回复
热议问题