Skip to content

Instantly share code, notes, and snippets.

@zbicin
Created August 1, 2015 18:35
Show Gist options
  • Select an option

  • Save zbicin/2b3fdf538936287c1a96 to your computer and use it in GitHub Desktop.

Select an option

Save zbicin/2b3fdf538936287c1a96 to your computer and use it in GitHub Desktop.
Directive focusing an element when given scope variable becomes boolean true.
/*
* Directive focusing an element when given scope variable becomes boolean true.
* If the variable becomes equal to boolean false the element is blurred.
* Usage: <input type="text" focus-on="someScopeVariable === 1" />
*/
angular.module('FocusOnDirective').directive('focusOn', ['$timeout', function ($timeout) {
'use strict';
return {
restrict: 'A',
scope: {
focusOn: '='
},
link: function (scope, element) {
scope.$watch('focusOn', function (newValue, oldValue) {
if (newValue !== oldValue) {
if (newValue === true) {
$timeout(function () {
element[0].focus();
}, 0);
} else if (newValue === false) {
$timeout(function () {
element[0].blur();
}, 0);
}
}
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment