user818700
user818700

Reputation:

Focusing an input field in Ionic not working

I've been doing my research and it seems that this is not an uncommon issue or question in the Ionic community. I have a simple form with a view inputs:

<input type="text" id="firstName" placeholder="First Name" ng-model="registerData.firstName">
...

In my controller I then try to focus the field:

document.getElementById("firstName").focus();

Of course it doesn't work, so as a few posts that I've seen suggests, I have to add the Ionic Keyboard Plugin . I do so by running:

cordova plugin add https://github.com/driftyco/ionic-plugins-keyboard.git

And then I apparently have to set this in my config.xml as wel:

<preference name="KeyboardDisplayRequiresUserAction" value="false"/>
<feature name="Keyboard">
  <param name="ios-package" onload="true" value="IonicKeyboard"/>
</feature>

And then apparently everything should work... but it doesn't. Is there something I'm missing?

Upvotes: 7

Views: 17867

Answers (1)

Mudasser Ajaz
Mudasser Ajaz

Reputation: 6257

You could use autofocus, but that will work only first time you open page,so try this directive. It works like a charm for me.
JS:

angular.module('app').directive('focusMe',['$timeout',function ($timeout) {
  return {
    link: function (scope, element, attrs) {
      if (attrs.focusMeDisable === "true") {
        return;
      }
      $timeout(function () {
        element[0].focus();
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
          cordova.plugins.Keyboard.show(); //open keyboard manually
        }
      }, 350);
    }
  };
}]);

HTML:

<input type="text" id="firstName" placeholder="First Name" ng-model="registerData.firstName" focus-me focus-me-disable={{disableFlag}}>

Upvotes: 10

Related Questions