In the code below, I cannot simply call "element[0].focus()" but instead need to wrap this in either $timeout or $evalAsync?
Full code and working example of the problem: http://plnkr.co/qW20iZ5D1tUpQ6gL6shZ?p=preview
app.setFocus = function ($timeout, $rootScope) {
return {
restrict: 'A',
link: function (scope, element, attr) {
scope.$watch(attr.setFocus, function (newValue, oldValue) {
if (newValue === true && newValue != oldValue) {
var performWork = function() {
element[0].focus();
console.log(document.activeElement);
};
// Question: Why do I need to execute performWork()
// any of the two commented out ways below
// in order for this to work? Why does not just
// calling performWork() work?
//$timeout(performWork, 0);
//$rootScope.$evalAsync(performWork);
performWork();
}
});
}
};
};
app.setFocus = function ($timeout, $rootScope) {
return {
restrict: 'A',
priority: 1,
The problem happens because ngClass manipulates the DOM element after you set the focus, and probably it's responsible for losing the focus.
ngClass $watch to run before your directive's $watch.ngClass has no priority ( defaults to 0)So by giving a priority > 0 to your directive you assure that ngClass $watch is registered before your directive's $watch
have fun!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With