【问题标题】:Angular cursor positioning issue角光标定位问题
【发布时间】:2016-02-22 21:05:11
【问题描述】:

我有一个特殊的问题。我有一个指令,它只允许在输入文本框中输入字母。它在大多数情况下工作正常,除了一个。 当我尝试编辑字符串的中间部分时,它会进行编辑,但控件会转到字符串的末尾,然后我必须再次将其放置到我要编辑的字符串位置。示例 变种测试 = 'abcdefg';当我更改除字母“g”以外的任何字母时,光标会移到整个单词的末尾。我希望它在更改的字母之后。任何帮助将不胜感激 下面是部分指令代码

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;
            });
        }

【问题讨论】:

    标签: javascript jquery angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    不确定您是否解决了问题,但我遇到了同样的问题,每次我在输入中间删除一个字符时,它都会让我跳到输入的末尾。

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

        //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;
        });
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2015-01-21
      • 2015-01-21
      相关资源
      最近更新 更多