0

I want to add a click handler to an ng-focus callback, to start listening to all future click events. But when focus is initiated by a click, the click handler fires immediately as well. I can solve the problem with a $timeout, but this is a hack and it goes against everything I stand for. What have I become?!

My HTML:

<input type="text" name="q" ng-focus="inputFocus($event)" />

This .js works (this is inside a directive's link function):

scope.inputFocus = function (e) {
    scope.displayHistory = true;
    $timeout(function () {
        $document.on('click', hideHistory);
    }, 200)
};

function hideHistory() {
    scope.displayHistory = false;
    scope.$digest();
    $document.off('click')
};

I want the following to work, but the problem is that the click callback fires immediately. As you might expect, if I tab to this field, the click callback does not get called. But if the focus event is triggered by a click, hideHistory gets called.

scope.inputFocus = function (e) {
    scope.displayHistory = true;
    $document.on('click', hideHistory);
};

I tried calling e.stopPropagation() and e.stopImmediatePropagation() but these solutions were not effective either.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Brett
  • 2,775
  • 4
  • 27
  • 32
  • What about setting a boolean in the click function to check if focus has been fired, then only run the click function once focused equals true. – mrdeleon Jun 12 '15 at 14:20

1 Answers1

0

Have you tried e.preventDefault(); ?

Anyway you can provide a fiddle to illustrate exactly what's going on?