Skip to content

Instantly share code, notes, and snippets.

@danrigsby
Created August 25, 2014 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danrigsby/643a812edb6f77926f00 to your computer and use it in GitHub Desktop.
Save danrigsby/643a812edb6f77926f00 to your computer and use it in GitHub Desktop.
A simple angular directive to set focus to an element
.directive('setFocus', function ($timeout) {
return function ($scope, $element, $attr) {
if($attr.setFocus !== false) {
var timeout = 750; // wait 750 ms before evaluating
var focus = true;
if ($attr.setFocus) {
// if we have focus criteria, then evaluate it against the scope (ex: set-focus="myValue === 1")
focus = $scope.$eval($attr.setFocus);
}
// if we need to set focus to this element, then wait for the timeout and set focus
if (focus) {
$timeout(function () {
$element[0].focus();
}, timeout);
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment