1

I created a simple directive which triggers focus event on input to show tooltip

.directive('tooltipValidationObserver', ['$timeout', function($timeout) {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function($scope, element, attrs, ngModel) {
            $scope.$watch(function() { return ngModel.$invalid; }, function(newVal, oldVal) {
                $timeout(function() {
                    $('#' + attrs.id).trigger('focus');
                });
            });
        }
    }
}])

It works perfectly if I use attrs.id, but if I want to perform

$(element).trigger('focus')

element is undefined, when in link function it's defined on linking phase.. and undefined in watch function. Why? In watch function I can obtain all available variables (such as $scope, attrs, ngModel) but not the element..

champion
  • 339
  • 1
  • 2
  • 12
  • Probably unrelated, but you simply want `element.trigger('focus')`. `element` is already a jQuery object. – JB Nizet May 01 '15 at 15:05
  • 1
    did u try to `console.log()` the `element` inside `link` function as , `console.log(element)` ? – Kalhan.Toress May 01 '15 at 15:12
  • Yes of course, thanks, I forget that element is already jquery object – champion May 01 '15 at 15:13
  • K.Toress, yes! That variable exists when I tried to log it to console.. Before I set breakpoint in chrome developer tools in code to see that variable and it's was undefined.. So, now I don't understand why that variable in chrome developer tools available only if I use it. I mean when I perform debugging with breakpoints in the inner $watch function. Magic. – champion May 01 '15 at 15:21
  • 1
    @champion I have run into that problem before as well and it can be frustrating. Check out this explanation http://stackoverflow.com/questions/28388530/why-does-chrome-debugger-think-closed-local-variable-is-undefined – ken4z May 01 '15 at 15:24
  • @ken4z thank's for information! yes it not so obvious and very confusing.. – champion May 01 '15 at 15:26
  • So is this question only debugger related? Otherwise you might want to replicate the issue in Plunker - http://plnkr.co/edit/EZLm5Q3IXlTusfqKZvcP?p=preview – Pavel Horal May 01 '15 at 15:35

1 Answers1

0

use,

$(element[0]).trigger('focus');

in the link function element is the jqLite-wrapped element, try to console.log(element) and expand the output and you can see the 0 index is the actual dom element. here is a DOC

get the actual dom element by element[0] and we create jquery reference as $(element[0]) to that element and trigger the focus event on it. hope this helps.

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92