1
votes

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..

1
Probably unrelated, but you simply want element.trigger('focus'). element is already a jQuery object. - JB Nizet
did u try to console.log() the element inside link function as , console.log(element) ? - Kalhan.Toress
Yes of course, thanks, I forget that element is already jquery object - champion
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
@champion I have run into that problem before as well and it can be frustrating. Check out this explanation stackoverflow.com/questions/28388530/… - ken4z

1 Answers

0
votes

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.