Reputation: 3391
I have an input
tag in my HTML which can contain a very long number, sometimes longer than can be viewed.
This field can get inputs from the keyboard or from some digits buttons that I have in my html page.
If I enter digits from the keyboard I always can see the last entered digits even if the number is longer than can be viewed. But if I enter digits to the field from the digit buttons and it get longer than the field, I can see the first digits instead of the last entered digits.
Is there any way to set the text that I always will see the last entered digits when the number is longer than can be viewed?
input field:
<input id="numberEntry" type="tel" data-ng-model="numberInput" data-ng-change="commands.inputTextChanged.execute();" class="numberEntry"/>
.numberEntry {
width: 100%;
text-align: center;
font-size: 28px;
}
This is the code which adds the digits (inline '4' for the ex.) to the end of the number (by AngularJS):
this.mScope.numberInput = this.mScope.numberInput + "4";
Upvotes: 3
Views: 672
Reputation: 27062
You probably should separate out this behaviour in a directive. There are a few ways to do this, but one would be to add a directive to the input that changes the caret position if the model has changed, but only if it doesn't have focus (i.e. the change came from Angular, say from a click on a button, rather than the user typing in).
app.directive('onChangeCaretEnd', function($document) {
return {
scope: {
'ngModel': '='
},
link: function(scope, element, attrs) {
scope.$watch('ngModel', function(newValue) {
var hasFocus = (element[0] == $document[0].activeElement);
// Set focus if doesn't have focus
if (!hasFocus) {
element[0].focus();
// Chrome doesn't seem to need the line below, but FF does.
element[0].selectionStart = element[0].selectionEnd = newValue.length;
}
});
}
};
});
And the directive can be used on an input that uses ngModel
:
<input id="numberEntry" type="tel" data-ng-model="numberInput" data-on-change-caret-end />
You can see this in action at the following Plunkr
http://plnkr.co/edit/NgFS8WWfEDKpTtVI71uq?p=preview
However, there is a bit of an annoyance in Chrome. When a text input loses focus in Chrome, then it seems to scroll back to its beginning. This happens on the click of any other element, so the above directive isn't perfect. Firefox seems to keep the scrolled position on blur however.
To be honest, I would probably advise changing the interface to either only allow a maximum number of characters entered, by using a maxlength
attribute, or always make all characters entered visible, say by using a <textarea>
element instead. There are various plugins available (or you could write your own custom directive) to dynamically adjust the height of the textarea, so it will always show all the characters entered.
Upvotes: 1