benjamincharity
6/16/2015 - 3:07 PM

Keep a phone number within an input formatted while keeping the model clean with only numbers

Keep a phone number within an input formatted while keeping the model clean with only numbers

export function PhoneInputDirective(
    $filter, $browser, $timeout
) {
    'ngInject';

    const directive = {
        restrict: 'A',
        scope: {
            phoneInput: '=',
        },
        link: linkFunction,
    };

    return directive;


    /**
     * Link
     */
    function linkFunction($scope, $element, $attrs) {
        const maxLength = 10;

        // Watch for model changes
        $scope.$watch('phoneInput', (newValue, oldValue) => {
            update(newValue);
        });

        // Bind to change in case the model was updated manually
        $element.bind('change', () => {
            // Have to do this or changes don't get picked up properly
            $timeout(() => {

                const currentValue = $filter('telephone')($element.val(), 'clean');
                update(currentValue);

            });
        });

        // Bind to keydown for input changes
        $element.bind('keydown', () => {

            // Have to do this or changes don't get picked up properly
            $timeout(() => {

                const currentValue = $filter('telephone')($element.val(), 'clean');
                update(currentValue);

            });

        });




        /**
         * Update the view and the model
         *
         * @param {String} currentValue
         */
        function update(currentValue) {

            // Set the masked input value manually
            if (currentValue) {
                $element.val($filter('telephone')(currentValue, 'format'));
            } else {
                $element.val(currentValue);
            }

            // Assign the clean value back to the model
            $scope.phoneInput = currentValue;
        }


    }

}