Detecting Touch on ionContent


#1

Hey guys, I’m trying to detect when an input field has been tapped in the following way, but I also need to know when I’ve tapped out of it (out of focus), so that I can show/hide other elements in the view.

Controller:

var searchBox = angular.element(document.querySelector('input'));

$ionicGesture.on('tap', function(e) {
  ctrl.hasHeader = false;
  $scope.$digest();
}, searchBox);

I’ve tried the following and it doesn’t work.

var ionContent = angular.element(document.querySelector('ion-content'));

$ionicGesture.on('tap', function(e) {
  ctrl.hasHeader = true;
  $scope.$digest();
}, ionContent);

I’m sure there’s a better way… Thanks in advance.


#3

I wouldn’t bother detecting a touch event. I’d just use the ‘focus’ and ‘blur’ events in a directive.

.directive("detectFocus", function() {
  return {
    "restrict" : "AC",
    "link" : function(scope, elem, attrs) {

      elem.on("focus", function() {
        console.log(attrs.name + " has focus!");
      });
      
      elem.on("blur", function() {
        console.log(attrs.name + " lost focus");
      });
      
            
    }
  }
})

#4

Nice solution. The directives works. The console messages shows what happens. But how do I use it in my code. How do I detect a text fileld has got focus.

BTW attrs in the console statement is undefined


#5

Got a solution with:

'use strict';

app.directive('detectFocus', ['$rootScope', function($rootScope) {
  return {
    'restrict' : 'AC',
    'link' : function(scope, elem, attrs) {

      elem.on('focus', function(attrs) {
        console.log(attrs.name + ' has focus!');
        scope.$apply( function() {
          scope.$emit('elemHasFocus', {
              message: elem[0].placeholder
          });
        });
      });
      
      elem.on('blur', function(attrs) {
        console.log(attrs.name + ' lost focus');
      });
      
            
    }
  };
}]);

The event you can listen to. Put an attribute of the field you like.