Skip to content

Instantly share code, notes, and snippets.

@bbrown
Created June 30, 2015 19:10
Show Gist options
  • Select an option

  • Save bbrown/fd99490ec8073fa294f6 to your computer and use it in GitHub Desktop.

Select an option

Save bbrown/fd99490ec8073fa294f6 to your computer and use it in GitHub Desktop.
Angular directive to watch a model and focus (or blur) on its truth (or falsity)
// FROM http://stackoverflow.com/a/14837021/20595
angular.module("app").directive("focusOn", function($timeout, $parse)
{
return {
restrict: "A",
link: function(scope, element, attrs)
{
var model = $parse(attrs.focusOn);
var focusListener = scope.$watch(model, function(value)
{
if (value === true)
{
$timeout(function()
{
element[0].focus();
});
}
});
element.on("blur", function()
{
$timeout(function()
{
scope.$apply(model.assign(scope, false))
}, 50);
});
scope.$on("$destroy", function()
{
focusListener();
element.off("blur");
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment