簡體   English   中英

角度光標定位問題

[英]Angular cursor positioning issue

我這里有一個特殊的問題。我有一條指令,只允許在輸入文本框中輸入字母。 除了一個以外,它在大多數時間都能正常工作。 當我嘗試編輯字符串的中間部分時,它會進行編輯,但控件會移至字符串的末尾,然后再次將其放置在要編輯的字符串位置。示例var test ='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;
            });
        }

不知道您是否解決了問題,但是同樣的問題是,每次我在輸入中間刪除一個字符時,都會跳過我到輸入末尾。

關於您的代碼,我不得不

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

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM