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?
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?
- Read How do I “think in AngularJS” if I have a jQuery background? it will help you in longer run – Satpal Commented Jul 23, 2014 at 8:41
- So you don't bind in Angular? What do you do then? – Kousha 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 – Fad Commented Jul 23, 2014 at 8:42
-
@KemalFadillah, do you mean create a directive for
input
that is restricted to an element? – Kousha Commented Jul 23, 2014 at 8:43 - @Kousha I'd have a look at MajoB's answer, another question here on SO (stackoverflow./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. – user1364910 Commented Jul 23, 2014 at 8:48
2 Answers
Reset to default 3You can add ngFocus directive to all input fields: https://docs.angularjs/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
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(){});
}
}
});