Skip to content

Instantly share code, notes, and snippets.

@mlynch
Last active August 24, 2022 15:03
Show Gist options
  • Save mlynch/dd407b93ed288d499778 to your computer and use it in GitHub Desktop.
Save mlynch/dd407b93ed288d499778 to your computer and use it in GitHub Desktop.
AngularJS Autofocus directive
/**
* 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();
});
}
}
}]);
@ortichon
Copy link

Great, thank you

@aarongray
Copy link

This directive was working great with an earlier version of Angular 1.4, but I recently upgraded to Angular 1.4.10, and started getting this error: Uncaught TypeError: $exceptionHandler is not a function. The solution was to inject $exceptionHandler in addition to $timeout into the directive. I believe this is because $timeout delegates any exceptions that occur within the function to the $exceptionHandler.

See: https://docs.angularjs.org/api/ng/service/$timeout

@MarcMouallem
Copy link

Like a boss!

@iuprade
Copy link

iuprade commented Sep 6, 2016

awesome

@DrakeXiang
Copy link

The $timeout to the rescue!!!

@sokhomhuy
Copy link

awesome

@maxthevoice
Copy link

Thanks!

@joryschmidt
Copy link

wonderful, thank you sir

@jeponkz
Copy link

jeponkz commented Sep 18, 2020

how to add autofocus conditionally? so if expression is true add "autofocus" attribute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment