I have a angular directive, which is loaded from a template. The directive has a textbox, and I set the focus programmatically to this text box, once the directive is rendered on the page. For this , I am using $timeout, so that the focus is set after rendering, like this :
$timeout(function() {
$element[0].focus();
});
now, the user types in something, and uses backspace to delete characters one at a time. The UI currently works such that when the user query is 0 characters, it leads to a state reload, so the whole page is loaded again, along with the directive.
So, sometimes, when the user presses backspace for long enough, and deletes all the characters, the browser back functionality is fired (because the page is loaded, and the directive template is reloaded but the programmatic focus hasn't been set on the input element yet). This un-focus is not visible to the user, but leads to erratic behaviour.
One way to achieve this is to somehow not reload the page on 0 characters, which in this case is used for cleaning up and re-initializing. But i am looking for some alternatives to this, also is this correct behavior from the browser?
This is the relevant directive template:
<input type="text"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
ng-click="Click()"
autofocus>
and this is the relevant part of the autofocus directive:
restrict: 'A',
link : function($scope, $element) {
$timeout(function() {
$element[0].focus();
});
}
Effectively, what I see is a behaviour like :
$timeout(function() {
$element[0].focus();
},100);
that is, if the element is focused after 100 ms, then within these 100 ms, the user may actually press backspace and trigger browser back functionality as the input element is not focused, but when timeout delay is 0, i don't expect that to happen (well, i do, because 0 is not actually 0, but ideally no).