首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度光标定位问题

角度光标定位问题
EN

Stack Overflow用户
提问于 2016-02-23 05:05:11
回答 1查看 531关注 0票数 0

我这里有个奇怪的问题..我有一个指令,它只允许在输入文本框中使用字母。它在大多数情况下都工作得很好,只有一个例外。当我尝试编辑字符串的中间部分时,它会进行编辑,但控件会转到字符串的末尾,然后我必须再次将其放到要编辑的字符串位置。例如var test = 'abcdefg';当我更改除字母"g“之外的任何字母时,光标将移动到整个单词的末尾。我希望它在被更改的字母之后。任何帮助都将在下面的part指令代码中获得

代码语言:javascript
复制
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;
            });
        }
EN

回答 1

Stack Overflow用户

发布于 2016-05-11 19:34:04

不知道你是否已经解决了你的问题,但是我遇到了同样的问题,每次我在输入中间删除一个字符,它就会跳到输入的末尾。

关于你的代码,我不得不这样做

代码语言:javascript
复制
    //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;
    });

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35563817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档