I found some JavaScript functions to set Cursor position in textarea, I angularised  them to implement this functionality using AngularJS.

Markup

Caret Positon :<br/>
<input type="number" ng-model="caretPos"/><br/><br/>
<textarea id="myTextArea">
This is sample text for testing purpose
</textarea><br/><br/>
<button ng-click="setCaretToPos()">Set Caret Position</button>

Script

$scope.caretPos = 6;

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

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

3 comments:

  1. Replies
    1. For 1.4.7, you have to register controller like below

      myApp.controller('myCtrl', myCtrl);

      Delete
  2. Reading your blogs is therauptic. Keep sharing. I love them Are you also searching for Assignment Help UAE? we are the best solution for you. We are best known for delivering cheap assignments to students without having to break the bank

    ReplyDelete

Blogroll

Popular Posts