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.
Problem
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.
Solution
Javascript
HTML
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());
Result
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.
Pingback: AngularJS Highlights: Week Ending 11 August 2013 | SyntaxSpectrum
Hi.. Nice post. I found another useful directive for blur event in angular JS in this post : http://coding-issues.blogspot.in/2013/10/angularjs-blur-directive.html
Pingback: AngularJS Form Validation ♥ Scotch
Nice post, it’s very useful.
You are a hero!
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
Guys, can any one help with it..
i jus wanna update the field only wen field is blurred but now i have harcored the model options in html i need regex to be done in parser and round of logic in blur event.
http://plnkr.co/edit/wyBJvLYV7q6i0TTZpGLB?p=preview
Check with it
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):
this.focusInput();