Skip to content

Instantly share code, notes, and snippets.

@benjamincharity
Last active February 10, 2016 13:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamincharity/d7e3d9401bb6c70c7861 to your computer and use it in GitHub Desktop.
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
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