Seeking a solution to address a bug noticed while utilizing a custom Angular directive in conjunction with Chrome's autofill feature. The directive is designed for a phone number field, automatically adding dashes "-" to enhance user experience by eliminating the need for manual dash input.
Displayed below is the directive:
app.directive("phoneNumberValidator", function () {
return {
require: "ngModel",
restrict: "A",
link: function (scope, elem, attrs, ctrl) {
var domElement = elem[0]; // Access DOM element
var phoneNumberRegex = new RegExp("\\d{3}\\-\\d{3}\\-\\d{4}"); // Define phone number regex pattern
var cursorIndex; // Index for cursor placement
// Create parser to modify and validate phone numbers
ctrl.$parsers.push(function (value) {
if (typeof value === "undefined" || value === null || value == "") {
ctrl.$setValidity('invalidFormat', true);
return undefined;
}
var prevValue, nextValue;
prevValue = value;
nextValue = value.replace(/[\D]/gi, "");
if (nextValue.length >= 4 && nextValue.length <= 6) {
nextValue = nextValue.replace(/(\d{3})(\d{3})?/, "$1-$2");
} else if (nextValue.length >= 7 && nextValue.length <= 10) {
nextValue = nextValue.replace(/(\d{3})(\d{3})(\d{4})?/, "$1-$2-$3");
}
cursorIndex = domElement.selectionStart;
if (prevValue != nextValue) {
ctrl.$setViewValue(nextValue);
} else {
ctrl.$render();
}
if (cursorIndex == 4 || cursorIndex == 8) {
cursorIndex = cursorIndex + 1;
}
var valid = phoneNumberRegex.test(value);
ctrl.$setValidity('invalidFormat', valid);
domElement.setSelectionRange(cursorIndex, cursorIndex);
return value;
});
}
}
});
The issue arises when Chrome autofills the field. Using the Batarang extension (Batarang Extension Link), I can observe the scope values within the page. If Chrome auto-populates my phone number field with "1234567899," the corresponding Angular phone field's value in my $scope
remains as 1234567899 instead of 123-546-7899.
Inserting a breakpoint in my directive confirms that it executes upon Chrome's autofill action, however, the $scope.PhoneNumber
field retains the unfilled value. Essentially, the $viewModel updates correctly during autofill, but not the $modelValue.
Is there a method to programmatically adjust the $modelValue
to display the correct value in $scope.PhoneNumber
post Chrome autofill?