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

2 comments:

  1. not working for version 1.4.7

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

      myApp.controller('myCtrl', myCtrl);

      Delete

Blogroll

Follow this blog by Email

Popular Posts