13

When I surround my input with ng-if, after hide and show the autofocus attribute does not take effect:

Here is the code:

  <!DOCTYPE html>
<html ng-app>

  <head>
    <script data-require="angularjs@1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-init="view={}; view.show = true">
    <button ng-click="view.show = !view.show">{{view.show ? "hide" : "show"}}</button>
    <div ng-if="view.show">
      <input autofocus />
    </div>
  </body>
</html>

And here is the plunker: http://plnkr.co/edit/k7tb3xw5AsBYrhdlr3bA?p=preview

Just click on hide and after that on show and you will see the autofocus does not working!

In Chrome is working only on the first show, in FF and IE it's not working at all!

cheziHoyzer
  • 4,803
  • 12
  • 54
  • 81

3 Answers3

20

The problem is the attribute autofocus isnt an Angular directive. It is a browser supported specification of the <input> element. If you want this to work as intended across multiple browsers and auto focus every time you click hide/show you will need to make a directive.

I took this directive right off Github Gist, credit to mlynch for building this directive.

Heres a working example of your application

angular  
    .module('App', [  
        'utils.autofocus',
    ]);
    
/**
 * the HTML5 autofocus property can be finicky when it comes to dynamically loaded
 * templates and such with AngularJS. Use this simple directive to
 * tame this beast once and for all.
 *
 * Usage:
 * <input type="text" autofocus>
 * 
 * License: MIT
 */
angular.module('utils.autofocus', [])

.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link : function($scope, $element) {
      $timeout(function() {
        $element[0].focus();
      });
    }
  }
}]);
<!DOCTYPE html>
<html ng-app="App">

  <head  ng-init="view={}; view.show = true">
    <script data-require="angularjs@1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <button ng-click="view.show = !view.show">{{view.show ? "hide" : "show"}}</button>
  </body>
  
  <div ng-if="view.show">
    <input autofocus />
  </div>

    <script src="script.js"></script>
</html>
ug_
  • 11,267
  • 2
  • 35
  • 52
  • 1
    I would like to add one thing to your solution - prefix for directive. Like registering as `abcAutofocus` in `directive(...)` as using as `abc-autofocus` in HTML template to avoid confusing which solution is used - pure HTML or Angular directive. – Radek Anuszewski Mar 24 '17 at 14:53
  • Greaaaaaat solution. Thanks – Soldeplata Saketos Oct 12 '17 at 14:12
  • alternative would be to call ``angular.element('[autofocus]').trigger('focus');`` manually after button was clicked or response received – Philipp Wirth Jan 30 '21 at 10:50
3

You can use a directive for this. Plunker Demo

angular.module('myApp', []).directive('focusMe', function($timeout) {
    return {
        scope: {
            focusMeIf:"="
        },
        link: function ( scope, element, attrs ) {
            if (scope.focusMeIf===undefined || scope.focusMeIf) {
                $timeout( function () { element[0].focus(); } );
            }
        }
    };
});

You could also define a condition in it in focus-me-if attribute in it.

Hope it helps.

M. Junaid Salaat
  • 3,765
  • 1
  • 23
  • 25
-1

First of all you have to wrap the div and it's content inside the body element. You have it outside. please correct it.

Input element should not be blank and may not work sometimes. please add some more attribute like name and type="text" or appropriate. This is html5 feature and should start with <!DOCTYPE html>.

Please Note : The autofocus attribute of the input tag is not supported in Internet Explorer 9 and earlier versions.visit here for more details