Skip to content

Instantly share code, notes, and snippets.

@cyberdante
Last active September 20, 2017 14:56
Show Gist options
  • Save cyberdante/c2cb4f407c8048a4511adb252f5554a3 to your computer and use it in GitHub Desktop.
Save cyberdante/c2cb4f407c8048a4511adb252f5554a3 to your computer and use it in GitHub Desktop.
Angular 1.x directive to focus on an input
(function (angular) {
"use strict";
focusElemDirective.$inject = ['$timeout', '$parse'];
function focusElemDirective($timeout, $parse) {
return {
link: function (scope, element, attrs) {
var input = $parse(attrs.focusElem);
scope.$watch(input, function (value) {
if (value) {
$timeout(function () {
element[0].focus();
});
}
});
// on blur:
element.bind('blur', function () {
scope.$apply(input.assign(scope, false));
});
}
};
}
angular.module("Shared.Directives")
.directive("focusElem", focusElemDirective);
})(angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment