I have a directive to auto focus the next input as below. The project is angularJs for Ionic. It works in another project (which is phonegap based - not ionic) but in this ionic project it's not playing ball. The markup is the same.
(function() {
'use strict';
angular.module('appname.directives')
.directive('focus', [function() {
return {
restrict: 'A',
link: function($scope,elem) {
//after character keypress the focus switches to the next input
elem.bind('keyup', function(e) {
if (e.keyCode >= 48 && e.keyCode <= 90 || e.keyCode >= 96 && e.keyCode <= 105) {
if (elem[0].value !== "") {
if (elem.nextAll('input') && elem.nextAll('input').length > 0) {
elem.nextAll('input').first().focus();
} else {
elem.parent().parent().nextAll(".module__inner").first().find('input').first().focus();
}
}
}
});
}
};
}]);
})();
The html looks a bit like the below:
<div class="input-holder">
<input data-order="1" focus />
<input data-order="2" focus />
<input data-order="3" focus />
</div>
The strange thing is that in debugging I can see the code executing the line "elem.nextAll('input').first().focus();"
This does push down the native keyboard, but doesn't focus the next input. The weird thing is, when I 'tab' to the next input, then the directive works, and I can go back to the first and it auto tabs as expected.
In terms of binding the directive, i can debug and see it's firing so it cant be an issue related to that. The HTML is static, so it's no event delegation issue.
I'm perplexed by this, the only thing i keep coming back to is the fact that the initial .focus() doesnt seem to actually focus, and every other time it does.
I've tried wrapping it in a $timeout and $scope.$apply() but non seem to work.
Has anyone got any idea of something I can try?
EDIT
Strangely, it works as expected, when my Chrome dev tools is not open. It also doesn't work on device. I can't see what the difference here would be apart from maybe a slower execution cycle?
I have similar problem on the device.
If you are using Ionic + AngularJS, turns out you need to add the Ionic Keyboard plugin and these preferences in config.xml
<preference name="KeyboardDisplayRequiresUserAction" value="false" />
<feature name="Keyboard">
<param name="ios-package" value="IonicKeyboard" onload="true" />
</feature>
KeyboardDisplayRequiresUserAction preference is the one that is obstructing the focus function.