2017-05-03 35 views
0

我有一个代码插入一个字符串到文本输入框中的另一个字符串的中间。我想把光标放在刚刚插入的字符串的末尾。我可以看到放置后光标位置正确。但是,当页面完成渲染时,光标位于输入框的末尾。什么在移动我的光标位置?

我猜测其他东西在我放置它后触摸数据。我不熟悉代码库。任何关于如何跟踪这个指针的指针?是否有选择更改事件?

我借来的代码从这里做了定位:Set Cursor Position in Textarea using AngularJS

这里是我的代码:

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

回答

0

在任何人的情况下运行到这一点。我假设在这个页面上的一个观察者在我将光标放在我想要的位置之后重新渲染输入。与其试图找出正在做什么并改变观察者的顺序(可能会很脆弱),我决定将光标放置在页面呈现之后。搜索一下,在页面渲染后执行某些东西的解决方案是使用$ timeout,超时值为0(对我来说,这看起来像是一个巨大的黑客)。所以,像下面这样:

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

您将需要注入$超时到您的控制器。例如:

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