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.
I believe you could do it by using
.setSelectionRange()
on your input. I updated your example - see if this is what you wanted: http://plnkr.co/edit/bIJAPPAzkzqLIDUxVlIy?p=previewNote:
setSelectionRange
is not supported by IE8 (see https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setSelectionRange), so if you need to support IE < 9, you'll need to look for shims.I jsfiddled a working solution. So basically, you have to create a directive :
Your controller would be useless in that situation. You can invoke the directive like this (see : keypressdetector) :
See demo : https://jsfiddle.net/Lt7aP/3468/
I also had the same problem.
I thought to solve it creating an appropriate directive. You can find it here. Enjoy it!
Usage
Include directive, declare it by
caret-aware
attributeThen on the scope you'll have a variable
cursor
containing the position of the caret in the input namedmyname
.Nevertheless, this directive's controller exposes an API
getPosition
setPosition
For other usage examples see
example
directory of the above linked github repository.I think that the best approach for this is to make a reusable directive as we are dealing with DOM manipulation.
Link to the demo: http://plnkr.co/edit/qlGi64VO1AOrNpxoKA68?p=preview
You can see in the commented out part in the controller we can have access to this by using $element, but as this is DOM and controllers are not for DOM manipulation we need to make this into a directive.
I think that such kind of things look better in directives. For example:
Usage:
I used
setCaretPosition
function for cross browser cursor positioning from this answer.Demo: http://plnkr.co/edit/5RSgzvyd8YOTaXPsYr8A?p=preview