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-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.
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
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.