Skip to content

Instantly share code, notes, and snippets.

@janmarek
Created September 23, 2013 16:32
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 janmarek/6673210 to your computer and use it in GitHub Desktop.
Save janmarek/6673210 to your computer and use it in GitHub Desktop.
Angular focus directive
function FocusDirective() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
// add inputCtrl to scope
scope[ctrl.$name + 'InputCtrl'] = ctrl;
ctrl.$focused = false;
ctrl.enableEvents = true;
element.bind('focus', function (evt) {
if (ctrl.enableEvents) {
scope.$apply(function () {
ctrl.$focused = true;
});
}
}).bind('blur', function (evt) {
if (ctrl.enableEvents) {
scope.$apply(function () {
ctrl.$focused = false;
});
}
});
// watch for $focused change
scope.$watch(ctrl.$name + 'InputCtrl.$focused', function () {
if (ctrl.$focused) {
setTimeout(function () { // $apply is probably in progress, run this code later
ctrl.enableEvents = false; // avoid cycles
element[0].focus();
ctrl.enableEvents = true;
}, 0);
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment