diff --git a/src/mask.js b/src/mask.js index 1f738ab..db2edb9 100644 --- a/src/mask.js +++ b/src/mask.js @@ -74,7 +74,8 @@ angular.module('ui.mask', []) oldValue, oldValueUnmasked, oldCaretPosition, oldSelectionLength, // Used for communicating if a backspace operation should be allowed between // keydownHandler and eventHandler - preventBackspace; + preventBackspace, + isCtrlV; // detect copy paste var originalIsEmpty = controller.$isEmpty; controller.$isEmpty = function(value) { @@ -523,6 +524,8 @@ angular.module('ui.mask', []) var isKeyBackspace = e.which === 8, caretPos = getCaretPosition(this) - 1 || 0, //value in keydown is pre change so bump caret position back to simulate post change isCtrlZ = e.which === 90 && e.ctrlKey; //ctrl+z pressed + + isCtrlV = e.which === 86 && e.ctrlKey; //ctrl+v pressed if (isKeyBackspace) { while(caretPos >= 0) { @@ -670,6 +673,8 @@ angular.module('ui.mask', []) caretPos++; } oldCaretPosition = caretPos; + // Move caret to the end in case of paste event + caretPos = isCtrlV ? getMaskedInputLength(valMasked, originalPlaceholder) : caretPos; setCaretPosition(this, caretPos); } @@ -730,6 +735,19 @@ angular.module('ui.mask', []) } return 0; } + + // Get index of the last char that is not equal to placeholder + var getMaskedInputLength = function(masked, placeholder) { + if (masked === placeholder) { + return 0; + } + + var i = masked.length; + while(masked[i] === placeholder[i]) { + i--; + } + return i + 1; // place cursor after the found char + }; // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) {