trevoristall
10/5/2017 - 7:31 PM

format mac addresses in angularJS

format mac addresses in angularJS

angular
    .module('aq.ui')
    .directive('formatMac', () => {
        return {
            restrict: 'A',
            require: 'ngModel',
            link(scope, elem, attrs, ngModelCtrl: ng.INgModelController) {
                // formats text going to user (from model to view)
                const formatFromModel = (value) => {
                    if (value)
                        return value
                            // strip special characters and standardise format
                            .replace(
                                /[(\r?\n)\r\;\[\]\{\}\|\\\`\~\!\@\#\$\%\^\&\*\(\)\_\=\+\,\<\.\>\/\?]/gm, ''
                            )
                            .replace(/([0-9a-fA-F]{2})[\s|-]/gm, '$1:')
                            .toLowerCase();

                    return value;
                };
                // parses text going to model (from view to model)
                const parseToModel = (value) => {
                    return value
                        .trim()
                        .replace(/:/gm, ' ')
                        .toLowerCase();
                };

                ngModelCtrl.$formatters.push(formatFromModel);
                ngModelCtrl.$parsers.push(parseToModel);

                elem.on('input', () => {
                    const value = formatFromModel(elem.val());

                    if (value) {
                        ngModelCtrl.$setViewValue(value);
                        ngModelCtrl.$render();
                    }
                    scope.$apply();
                });
            }
        };
    });