Proper way to focus an input?

Not sure if i’m focusing input (for purpose of showing keyboard) correctly – Getting inconsistent behavior with focus().

In config.xml

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

In my controller, I’m calling this function when controller is loaded, and it properly focuses the input box.

 //focus decision name input
        $scope.focusDecisionName = function () {
            document.getElementById('decisionName').focus();
        }

however, when i call it thereafter, like when the user tries to continue to the next screen without naming the decision, it doesn’t popup the keyboard again in the ios simulator. The alert displays correctly though. I assume i am correct in calling it on alert dismiss (alertPopup.then())

    //alert if decision title is null
    $scope.alertNullDecision = function() {
        if($scope.decision.title == '') {


                var alertPopup = $ionicPopup.alert({
                    title: 'Woah there!',
                    template: 'Please name your decision before continuing'
                });
                alertPopup.then(function() {
                    $scope.focusDecisionName();
                });

            };
        }

You shouldn’t being doing any DOM manipulation in a controller, that should done with a directive.

Also install the ionic keyboard plugin

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

.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {

      $timeout(function() {
        element[0].focus(); 
      },750);
    }
  };
});

Thanks. Adding a timeout made it work. If i want to use a directive, what about the case when i want to refocus the input after the user does something? How would i access the directive’s function from the controller?

Then you would create a service, similar to $ionicScroll.Delagate

I am also facing the same problem. My input field is in a $ionicModal and i couldnt set auto focus when modal opens.

Any help appreciated.

did you try what mhartington said? Worked for me. Pretty sure you will need to provide more info if you want help

A simple solution is to all the HTML tag autofocus to the input.

1 Like

hello mgartington… im newbie here, what you mean with ‘‘directive’’?

I’m trying to put this .directive code in my app.js, and don’t work… I need put in another file?

Hi mhartington While clicking aero button in android device keyboard the focus should go next field … is there any way to do it …