Skip to content

Instantly share code, notes, and snippets.

@roidayan
Forked from mlynch/autofocus.js
Last active November 16, 2015 19:44
Show Gist options
  • Select an option

  • Save roidayan/6c3c5258fece37153b2c to your computer and use it in GitHub Desktop.

Select an option

Save roidayan/6c3c5258fece37153b2c 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="true">
*
* License: MIT
*/
angular.module('utils.autofocus', [])
.directive('autofocus', ['$timeout', function($timeout) {
return {
restrict: 'A',
scope: {
autofocus: '@'
},
link : function($scope, $element) {
if ($scope.autofocus === 'true') {
$timeout(function() {
$element[0].focus();
$element[0].scrollIntoView();
}, 100);
}
}
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment