0

In my master ng-controller, I want to bind ALL inputs to a focus event and trigger a function. What I have tried (and failed) so far were:

// This makes sense since it is not a bind
$('input').focus(function(){});

// This should work, but doesn't!
$('input').bind('focus', function() {});

What are my options? How can I bind all input to a focus?

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • Read [How do I “think in AngularJS” if I have a jQuery background?](http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background) it will help you in longer run – Satpal Jul 23 '14 at 08:41
  • So you don't bind in Angular? What do you do then? – Kousha Jul 23 '14 at 08:42
  • @Kousha Create a directive. The directive will be the one that handles this kind of thing. Also, see [ngFocus](https://docs.angularjs.org/api/ng/directive/ngFocus) – Kemal Fadillah Jul 23 '14 at 08:42
  • @KemalFadillah, do you mean create a directive for `input` that is restricted to an element? – Kousha Jul 23 '14 at 08:43
  • @Kousha I'd have a look at MajoB's answer, another question here on SO (http://stackoverflow.com/questions/22352564/angularjs-extend-input-directive), has a good couple of options for you on how to do this globally and/or for a more narrow scope in your application. –  Jul 23 '14 at 08:48
  • @KasperLewau, I went with a directive approach (see my answer) – Kousha Jul 23 '14 at 08:49

2 Answers2

3

You can add ngFocus directive to all input fields: https://docs.angularjs.org/api/ng/directive/ngFocus

<input type="text" ng-focus="controllerFunction()"></input>

Or read this answer how to do this globally for all inputs: AngularJS: extend input directive

Community
  • 1
  • 1
Marian Ban
  • 8,158
  • 1
  • 32
  • 45
  • No, this is too much to add an `ng-focus` to every input, specially that I would want to use that (maybe) for other functionalists. Worst comes worst, I'll just have a directive for input – Kousha Jul 23 '14 at 08:48
  • @Kousha Then I think this is the proper way how to do it: http://stackoverflow.com/a/24905165/1385075 – Marian Ban Jul 23 '14 at 08:54
2

Okay, I ended up using a directive for this purpose:

app.directive('input', function()
{
    return {
        restrict: 'E',
        link: function(scope, element, attrs)
        {
            element.bind('focus', function(){});
        }
    }
});
Kousha
  • 32,871
  • 51
  • 172
  • 296