1

I need some help to force execute an event from a directive before the event of the controller. My scenario is the next:

I have an input like that with a search method in my controller :

 <input type="text" name="searchText"
  required
  data-ng-model="searchText"
  data-ng-enter="search(searchText)" />

And a directive that register globally the keydown 13 ( ENTER key) which contains the next code:

 $document.bind("keydown keypress", function(event) {
                    if (event.which === 13) {
                       //do something
                    }
 }

If I place the cursor into the input and i press enter key, ng-enter is fired before the event of the global directive. There is some way to force execute directive event before controller?

I tried using priority for directive but wasn't the solution.

All help would be appreciatted.

1 Answer 1

2

The problem is that the event is bubbling up the DOM. The input event will always fire before the document event because the event will always bubble up.

If you want the document event to fire first, you can specify that you want it to run at the capturing phase (Note: Not supported if IE8 or lower). You can specify event capturing in the third parameter of the .addEventListener function:

function documentKeyEvent(event) {
    if (event.which === 13) {
        //do something
    }
}

$document[0].addEventListener("keydown", documentKeyEvent, true);
$document[0].addEventListener("keypress", documentKeyEvent, true);

Demo Here

Sign up to request clarification or add additional context in comments.

2 Comments

Another question. After handling the event in the directive, if i want to avoid the execution in controller how i can do it? I'm trying with event.stopPropagation(), stopInmediatePropagation and preventDefault, but doesn't work
@JorgeGuerola The document event will always fire first if you set it to capture. You cannot prevent its execution from within the input's directive event execution because it will execute second. I'm not sure I understand. Why do you want the document event to fire first if you want to be able to cancel it in the input event?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.