Focusing and bluring inputs


#1

This might be more angular related but since this forum focuses on mobile and I am using Ionic I will post it here.

I have a search form that shows when you press this icon. I am having trouble getting it to focus on the form field on the iOS simulator it self. Works great in chrome / ripple. Here is what I am doing:

These directives:

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

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

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

.factory('blur', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('blurOn', name);
    });
  }
})

And in my AppController:

$scope.search = function(s) {
    blur('searchInput');
    $scope.go('/search/' + s.query);
  };

  var showingSearch = false;

  $scope.toggleSearch = function() {
    showingSearch = ! showingSearch;

    if (showingSearch) {
      focus('searchInput');
    } else {
      blur('searchInput')
    }
  };

The focus nor the blur work on the iOS simulator. Another thing I noticed is, in order to focus on the input field, I have to hold down my mouse for longer than normal other wise it won’t select it (simulator only). I don’t know if thats just something with the simulator, I haven’t tried it on the device yet.

Any ideas? Thanks!


#2

iOS does not let you create focus unless specifically allowed in your config.xml.

You need this :

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


#3

Amazing. That did it, mostly. The keyboard still doesn’t go away when I call blur(). Best practice to perform that?


#4

Does the field you are blurring have focus? If not, the keyboard will not close. So, if the focus is on field1 and you trigger blur on field2, the keyboard will not hide.

This has been my experience at least.


#5

Looks like my blur directive isn’t even getting called. Can’t figure out why. It hits the factory but never hits the directive it self.