如何在md-datepicker中使用ngMask

时间:2016-11-04 02:50:55

标签: angularjs angular-material masking maskedinput

我正在尝试将ngMaskmaterial datepicker一起使用,但无效。

任何人,有任何想法如何让它一起工作?

一些ngMask示例: http://candreoliveira.github.io/bower_components/angular-mask/examples/index.html#/

1 个答案:

答案 0 :(得分:2)

这样的事情怎么样:

(function () {

    'use strict';

    /**
     * Setup a custom date formatter, I'm using moment for example
     */
    angular
        .module('awesomemodule')
        .constant('DEFAULT_DATE_FORMAT', 'DD/MM/YYYY')
        .config(['DEFAULT_DATE_FORMAT', '$mdDateLocaleProvider', dateConfig]);

    function dateConfig (DEFAULT_DATE_FORMAT, $mdDateLocaleProvider) {

        $mdDateLocaleProvider.formatDate = osDateFormatter;

        function osDateFormatter(date) {
            if (!date) {
                date = new Date();
            }

            return moment(date).format(DEFAULT_DATE_FORMAT);
        }
    }

})()


(function () {
    'use strict';

    /**
     * Decorate the mdDatepickerDirective to add ngMask
     */
    angular
        .module('awesomemodule')
        .config(['$provide', checkForNgMask]);

    function checkForNgMask ($provide) {

        $provide.decorator('mdDatepickerDirective', function ($delegate) {
        var directive = $delegate[0];

        var template = directive.template;

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

            if (R.has('osMask', tAttrs)) {
                var element = angular.element(originalTemplate);
                element.find('input').attr('mask', tAttrs.osMask);
                element.find('input').attr('ng-model', "ctrl.dateInput");//ng-model is required by ngMask
                return R.map(R.prop('outerHTML'), R.values(element)).join("");
            }

            return originalTemplate;
        };

        return $delegate;
    });

    }
})();

并使用像这样的指令

<md-datepicker ng-model="myAwesomeModel" os-mask="3?9/19/9999"></md-datepicker>