最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS - Bind Input to focus - Stack Overflow

programmeradmin1浏览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?

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?

Share Improve this question asked Jul 23, 2014 at 8:38 KoushaKousha 36.4k59 gold badges188 silver badges314 bronze badges 6
  • 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
 |  Show 1 more ment

2 Answers 2

Reset to default 3

You 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(){});
        }
    }
});
发布评论

评论列表(0)

  1. 暂无评论