Dealing with focus and blur in AngularJS directives

I’m developing an app where I’m using AngularJS. I was facing a problem how to set focus to some form elements. There are no ng-focus or ng-blur directives. So this is the way how I solve the problem. I’m not saying this is a great solution but this is how I solved it.
Screen Shot 2013-08-06 at 9.21.53 PM


I have a web service that sometimes requires from user to add some additional information. So for smoother user experience I would like to focus on form element that requires user “attention”. Basically I’m sending POST request to a web service and in the response from the server, user is asked to add some additional parameters (security credentials like: Captcha, GRID, …).
The task was to create a nice overlay (popup) on the page and then to focus on form element after such response from web service occurs.




It is really simple. I have scope variable $scope.focusField1/2 which is watched by custom directive my-focus. If this scope variable is changed to true it will fire focus event and focus listener will focus on the element where this change happened.
On blur event, I’ve created another directive my-blur which will evaluate the method for blurring. If the blur event occurs then the blur method is called ($scope.apply()) and focus variable will be changed back to false ($scope.eval());


Basically I’m not happy that I have to change scope values (model) to focus something on page (view), but I didn’t found anything better.
Let me now what you think about this solution.

8 thoughts on “Dealing with focus and blur in AngularJS directives

  1. Pingback: AngularJS Highlights: Week Ending 11 August 2013 | SyntaxSpectrum

  2. Pingback: AngularJS Form Validation ♥ Scotch

  3. Nath

    Hey, thanks for the post, I’m learning Angular and sometimes I have difficulties and your post helped me alot! I love JS but Angular it’s totally different to me, some times I think complicated when I’ll see, it’s too easy to resolve! lol

  4. begemot

    It is better to write a directive that publishes to the scope a method to focus the element where the directive is applied to.
    For example in HTML:

    The directive my-focus-method sets to ctrl.focusInput a function that can be used to set focus to the input (in the controller):


Leave a Reply

Your email address will not be published. Required fields are marked *