[英]Angular cursor positioning issue
I have a peculiar problem here.. I have a directive which allows only alphabetic letters in the input text box. 我这里有一个特殊的问题。我有一条指令,只允许在输入文本框中输入字母。 Its working fine for most of the time except one.
除了一个以外,它在大多数时间都能正常工作。 When I try to edit the middle part of the string, it does edit but the control goes to the end of the string and then again i have to place it to the string position where I want to edit.. Example var test = 'abcdefg';
当我尝试编辑字符串的中间部分时,它会进行编辑,但控件会移至字符串的末尾,然后再次将其放置在要编辑的字符串位置。示例var test ='abcdefg '; when i change any letter except the letter "g" the cursor goes to the end of the whole word.
当我更改除字母“ g”以外的任何字母时,光标将移至整个单词的末尾。 I want it to be after the letter that is changed.
我希望它在更改字母之后。 Any help will be appreciated Below is the part directive code
任何帮助将不胜感激下面是零件指令代码
link: function (scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$parsers.unshift(function (inputValue) {
var alphas = inputValue.split('').filter(function (s) { return (s.match(/[ A-Za-z\-']/g)); }).join('');
ngModel.$viewValue = alphas;
ngModel.$render();
return alphas;
});
}
Not sure if you've solved your issue, but I had the same issue where every time I deleted a character in the middle of the input, it would skip me to the end of the input. 不知道您是否解决了问题,但是同样的问题是,每次我在输入中间删除一个字符时,都会跳过我到输入末尾。
With regards to your code, I had to do 关于您的代码,我不得不
//Checks if the setSelectionRange method is available (not IE compatible)
//Otherwise use createTextRange() (IE compatible)
scope.setSelectionRange = function (input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
} else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd("character", selectionEnd);
range.moveStart("character", selectionStart);
range.select();
}
};
ngModelCtrl.$parsers.push(function (value) {
//Get the position the cursor was last at
var lastLetterPosition = element[0].selectionStart;
element.val($filter("uppercase")(value));
value = value.replace(/ /g, "").toLowerCase();
//I tried to do scope.$apply() to apply the change, but a digest cycle
//was already in progress, so scope.$evalAsync() adds the
//change to the end of the current digest cycle instead
//Manually set the position of the cursor to where the last position was
scope.$evalAsync(scope.setSelectionRange(htmlElement, lastLetterPosition, lastLetterPosition));
return value;
});
Hope that helps! 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.