How to trigger focus on state change?

Hi !

I do not succeed in triggering focus on a specific input.
It works at startup (with HTML5 autofocus or with a directive) but not once the user go back to an existing view.

Could you let me know of to do that ?

Thanks,
Theo

Not sure about this but

$scope.$on('$ionicView.enter', function() {
    //trigger input focus?
});

Actually the missing part is the “trigger input focus” !

For the state change I use :

$scope.$on(’$stateChangeSuccess’, function () {

});

document.querySelectorAll('[autofocus]')[0].focus(); ??

So ugly btw. Maybe a directive that get element and trigger focus?

This should get you in the right direction

.directive('focusMe', function($timeout) {
  return {
    link: function($scope, $element, $attrs) {
      $timeout(function() {
        $element[0].focus(); 
      },750);      
    }
  };
});

thats it.

Much better :stuck_out_tongue:

Thank you. But can you explain me how to trigger it from a controller please ?

No need to use a controller, you would apply this directive and when the element in active in the view, it will toggle focus

I’m just curious

The 750ms delay its for any special reason?

I mean, without it, $element its undefined

Hi !

Thanks again for your help.

For any reason it was not working on my side but I found this solution that made my day : http://stackoverflow.com/a/18295416/4347510

Usage

<input type="text" focus-on="focusMe"/>

app.controller('MyCtrl', function($scope, focus) {
    focus('focusMe');
});

Source

app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {
          elem[0].focus();
        }
      });
   };
});

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);
    });
  }
});

Well you’d need to wrap it in a time out to catch the next digest cycle in angular.
As for 750ms, no particular reason, just ended up being a happy delay :smile:

Hi,

Not working for me on iOs8 with iPad mini.
Cordova 4.2, ionic 1.0.0-rc.1-nightly-1155

No focus in field, no keyboard opening.
The view seems to blocked a few seconds, then if I touch the content, the input get the focus & the keyboard appears.
But Nav bar disappear until I scroll down.

Thanks for your help,

Try adding this line to your config.xml

    <preference name="KeyboardDisplayRequiresUserAction" value="false" />

Thanks for your help, I already did it.

Now, I did some cleanup in my installed plugins, and it’s working now, but it’s very long for the keyboard to open & the input to get the focus (~4 seconds)

I don’t know if it’s normal

@mhartington Everything looks fine today… Focus + keyboard displayed quickly on iOs & Android

Just don’t understand why…
Thanks for your help !