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?

6
  • Read How do I “think in AngularJS” if I have a jQuery background? it will help you in longer run Commented Jul 23, 2014 at 8:41
  • So you don't bind in Angular? What do you do then? Commented Jul 23, 2014 at 8:42
  • @Kousha Create a directive. The directive will be the one that handles this kind of thing. Also, see ngFocus Commented Jul 23, 2014 at 8:42
  • @KemalFadillah, do you mean create a directive for input that is restricted to an element? Commented Jul 23, 2014 at 8:43
  • @Kousha I'd have a look at MajoB's answer, another question here on SO (stackoverflow.com/questions/22352564/…), has a good couple of options for you on how to do this globally and/or for a more narrow scope in your application. Commented Jul 23, 2014 at 8:48

2 Answers 2

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

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

2 Comments

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 Then I think this is the proper way how to do it: stackoverflow.com/a/24905165/1385075
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(){});
        }
    }
});

Comments

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.