2017-05-03 34 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)