Created
September 23, 2013 16:32
-
-
Save janmarek/6673210 to your computer and use it in GitHub Desktop.
Angular focus directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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