简体   繁体   中英

What is moving my cursor position?

I have code that inserts a string into the middle of another string in a text input box. I want to put the cursor a the end of the string I just inserted. I can see that the cursor position is correct after I place it. But, by the time the page has finished rendering, the cursor is at the end of the input box.

I am guessing something else is touching the data after I place it. I am unfamiliar with the code base. Any pointers on how to track this down? Is there a selection changed event?

I borrowed the code to do the positioning from here: Set Cursor Position in Textarea using AngularJS

Here is my code:

    $scope.insertItem = function (insertText) {
       var currentText= $scope.markup;
       // The text is correctly stitched together. No issues here
       currentText = currentText.substr(0, $scope.curentPosition) + insertText + currentText.substr($scope.curentPosition);
       $scope.markup = currentText;
       // The caretPos is correctly calculated here
       $scope.caretPos = $scope.curentPosition + insertText.length;
       document.getElementById("markup").focus();
       $scope.setCaretToPos("markup", $scope.caretPos);
   }

   $scope.setCaretToPos = function (fieldName, caretPos) {
       $scope.setSelectionRange(document.getElementById(fieldName), caretPos, caretPos);
   };

   $scope.setSelectionRange = function (input, selectionStart, selectionEnd) {
       if (input.setSelectionRange) {
           // The code comes down this path
           input.focus();
           // document.getElementById("markup").selectionStart is correct after this lone
           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();
       }
   };

In case anyone runs into this. I assume a watcher on this page was re-rendering the input after I placed the cursor where I wanted it. Instead of trying to figure out what was doing that and change the order of watchers, which would likely be fragile, I decided to have the cursor placed after the page rendered. Searching around, the solution to have something execute after page rendering was to use $timeout with a timeout value of 0 (seems like a huge hack to me). So, something like the following:

$timeout(function () {
              $scope.setCaretToPos("markup", $scope.caretPos) },
         0);

You will need to inject $timeout into your controller. Something like:

ctrl.$inject = ['$scope', '$timeout'];
var ctrl = function ($scope, $timeout)

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