【问题标题】:Add Mask on md-datepicker angular js在 md-datepicker angular js 上添加掩码
【发布时间】:2018-03-15 11:55:30
【问题描述】:

我想在 Angular js 中为 md-datepicker 的日期选择器添加掩码输入

<md-datepicker ng-model="Date" style="position: relative; right: 24px">
</md-datepicker>

我尝试了以下但没有运气:( md-mask="19/39/9999" ui-mask="19/39/9999" MASK="19/39/9999"

【问题讨论】:

标签: angularjs datepicker mask


【解决方案1】:

以下 hack 是一种可能的解决方案。

它使用 ng-mask 库。

首先创建装饰器:

mdDatepickerDirective.$inject = ['$delegate', 'moment'];
function mdDatepickerDirective ($delegate, moment) {
    const directive = $delegate[0];

    const template = directive.template;
    const link = directive.link;
    directive.compile = function () {
        return function (scope, element, attrs, ctrl) {
            link.apply(this, arguments);

            if (attrs.myMask) {
                const inputNgModelControl = scope.ctrl.ngInputElement.controller('ngModel');

                inputNgModelControl.$formatters.push(function (value) {
                    const tempDate = moment(scope.ctrl.ngInputElement.controller('mdDatepicker').ngModelCtrl.$viewValue);
                    if (scope.ctrl.ngInputElement.controller('mdDatepicker').mode === 'month') {
                        return tempDate.isValid()? tempDate.format('MM/YYYY') : '';
                    } else {
                        return tempDate.isValid()? tempDate.format('DD/MM/YYYY') : '';
                    }
                });

                const watch = scope.$watch(function () {
                    return scope.ctrl.ngInputElement.controller('ngModel').$error.mask;
                }, function (newValue, oldValue) {
                    ctrl[0].$setValidity('mask', !newValue)
                });

                element.on('$destroy', function() {
                    watch();
                });
            }
        };
    };

    directive.template = function (tElement, tAttrs) {
        const originalTemplate = template.apply(this, arguments);

        if (tAttrs.myMask) {
            const element = angular.element(originalTemplate);
            element.find('input').attr('mask', tAttrs.myMask);
            element.find('input').attr('mask-validate', tAttrs.myMaskValidate);
            element.find('input').attr('ng-model', "ctrl.dateInput");

            let newTemplate = '';
            for (let i = 0; i < element.length; i++) {
                newTemplate += element[i].outerHTML;
            }
            return newTemplate;
        }
        return originalTemplate;
    };

    return $delegate;
}

然后在 app.config 阶段:

$provide.decorator('mdDatepickerDirective', mdDatepickerDirective);

原码:https://github.com/angular/material/issues/9976#issuecomment-332529645

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2018-01-16
    • 2018-03-06
    • 1970-01-01
    相关资源
    最近更新 更多