简体   繁体   中英

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'; when i change any letter except the letter "g" the cursor goes to the end of the whole word. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM