Reputation: 349
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..
Upvotes: 1
Views: 1077
Reputation: 21901
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.
Upvotes: 0