Wednesday 16 April 2014

Angular js auto focus for input box

Create a directive for autofocus and use where ever you need on the module.

I have explained the same using Angular 2/5 concept as well, for that please check this link:- Angular autofocus for input box - Angular 2/5.

Directive

 
 
// Common directive for Focus

angular.module('sampleapp').directive('focus',
function($timeout) {
 return {
 scope : {
   trigger : '@focus'
 },
 link : function(scope, element) {
  scope.$watch('trigger', function(value) {
    if (value === "true") {
      $timeout(function() {
       element[0].focus();
      });
   }
 });
 }
};
}); 
    
 

View

 
 
    Auto Focus : <input type="text" focus="true">

 

Demo

Play in fiddle

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Filtering concept in angular js

4. Show and Hide in angular

5. Simple client side sorting in angular


24 comments :

  1. Thanks! works like a charm

    ReplyDelete
  2. Thanks. I tweaked your example to help me solve my problem.

    ReplyDelete
  3. Thank you for this! Very helpful!

    ReplyDelete
  4. Thx for very simple solution

    ReplyDelete
  5. This doesn't seem to work when focus takes the value of a scope variable. Fiddle - http://jsfiddle.net/0qq8ntsp/

    ReplyDelete
  6. Sorry, this is the correct Fiddle - http://jsfiddle.net/au51zjux/3/

    ReplyDelete
    Replies
    1. How did you fix that? I am having the same problem. I cannot bind a variable to set focus or not.

      Delete
  7. Really sorry! Ignore my last two comments.

    ReplyDelete
  8. Works great. Thank you.

    ReplyDelete
  9. Works for me. Thanx

    ReplyDelete
  10. Why you have to create new directive for doing this while
    angularjs alreay has a built in method for this situation, just use ng-focus="true".

    ReplyDelete
  11. ^ This directive is for auto-focusing when a page loads as well.

    ReplyDelete
  12. thank you, this worked perfectly for me

    ReplyDelete
  13. Why $timeout is used?

    ReplyDelete
    Replies
    1. Instead of $apply I used $timeout which is better than $apply.

      Delete
  14. thanks, using trigger : '=focus' things get much better

    ReplyDelete
  15. friend can you give me a directive to restrict autofill data in textbox(autocomplete==off doesn't support)

    ReplyDelete
  16. Nice work thank you very much!

    ReplyDelete
  17. Thank you for your help.
    It works very well.
    awesome!!!!!!!!! :)

    ReplyDelete
  18. For some reason, I copied this code (only replaced the app name) and it does not work with modal windows. I tried renaming the focus to focusOnMe (focus-on-me in html) and it still did not work. I put in JS timeout to focus by id as a workaround (when the modal window is ready for events), but I can't figure out why it is not triggering.

    ReplyDelete
  19. Thank you. This directive helped me a lot :)

    ReplyDelete