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.

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


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