Search code examples
javascriptangularjsangularjs-scope

Set Caret position in Input with AngularJS


I need to change the caret position of an input, where a given number of digits is added (Example).

app.controller('MainCtrl', function($scope, $element, $timeout, $filter) {
  //$scope.val = '12';
  $scope.$watch('val', function(newValue, oldValue) {
    if (!isNaN(newValue)) {
      if (newValue.length > 3) {
        //Set Caret Position  
      }
    }
  });
});

Is it possible to do something like this example?

I need for example :

Input: 1234.

so the caret position will be 2.

New digit: 9

final: 12934

Thanks in advance.


Solution

  • I think that such kind of things look better in directives. For example:

    app.directive('caret', function() {
    
        function setCaretPosition(elem, caretPos) {
            if (elem !== null) {
                if (elem.createTextRange) {
                    var range = elem.createTextRange();
                    range.move('character', caretPos);
                    range.select();
                } else {
                    if (elem.setSelectionRange) {
                        elem.focus();
                        elem.setSelectionRange(caretPos, caretPos);
                    } else
                        elem.focus();
                }
            }
        }
    
        return {
            scope: {value: '=ngModel'},
            link: function(scope, element, attrs) {
                var caret = Number(attrs.caret);
                scope.$watch('value', function(newValue, oldValue) {
                    if (newValue && newValue != oldValue && !isNaN(newValue) && newValue.length > (caret + 1)) {
                        setCaretPosition(element[0], caret);
                    }
                });
            }
        };
    });
    

    Usage:

    <input ng-model='val' caret="2" />
    

    I used setCaretPosition function for cross browser cursor positioning from this answer.

    Demo: http://plnkr.co/edit/5RSgzvyd8YOTaXPsYr8A?p=preview