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

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.