Last active
February 10, 2016 13:09
-
-
Save benjamincharity/d7e3d9401bb6c70c7861 to your computer and use it in GitHub Desktop.
Keep a phone number within an input formatted while keeping the model clean with only numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment