AngularJS - input autofocus with ng-if not working

cheziHoyzer picture cheziHoyzer · Mar 28, 2016 · Viewed 11.2k times · Source

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="[email protected]" 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!

Answer

ug_ picture ug_ · Mar 28, 2016

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="[email protected]" 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>