1

I am using the swiper widget by Idangero, which allows me to pagify a form. However, since it loads all the controls up front, it is possible to tab into a field on the next page. I want to prevent this and I have found this jsfiddle that changes the page when tabbing.

It, however, uses regular javascript to listen to the focus event $('form')[0].addEventListener('focus'... I want to convert this to a more angular version using the $rootscope.$on (I also want it to blur out of the field instead of changing the page, but I think I can handle that) anyone know how to do this?

I'd rather not use the ng-focus directive because then I have to add it to the controls at the bottom and top of every page.

jgerstle
  • 1,674
  • 5
  • 25
  • 35

2 Answers2

2

General Answer for Angular events

$rootScope.$on is not used for element events - it is for events broadcast within your scope, using $rootScope.$boradcast or $rootScope.$emit.

If you want to listen to a focus event on an element, you can use the on() method in angular.element. This is almost identical to the equivalent jQuery method:

angular.element(document).find('form').on('focus', function() {
    // do something ...
});

Specific Explanation for form.onfocus

In your specific case however, the code is using event capture (addEventListener('focus, function() {}, true)'), rather than bubbling (See this answer for more info). This is required because form elements do not have their own focus event, only the input elements do, so they will not handle focus events bubbled up from the inputs.

Unfortunately jQuery (and hence Angular) only supports event bubbling (as explained in this answer and this one). A further issue is that jqLite built in to Angular does not support delegated events, where as full jQuery does.

This means your options are either:

  1. Add full jQuery to your page so you can use a delegated event:

    $('form').on('focus', ':input', function() {
        // do something
    });
    
  2. Use the vanilla JavaScript addEventListener with useCapture as you are now:

    $('form')[0].addEventListener('focus', function() {
        // do something
    }, true);
    

The $('form') code suggests you already have full jQuery installed, so options 1 should work for you.

Community
  • 1
  • 1
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
0

Nowadays it's best to just use ng-focus

Jayr Motta
  • 718
  • 1
  • 8
  • 26