jQuery plugin not found issue:
We can integrate jQuery plugin by creating a directory and initialise the plugin in the link function. There are many directives are available with this approach. Recently I wanted to integrate intl-tel-input jQuery plugin with an AngularJs project – fortunately couple of directives are available. I have tried with ng-intl-tel-input
The demo is very clear, but when tried to integrate, the angular element is not having the jQuery plugin.
var pluginApi = $element.intlTelInput;
This line will give nothing and we cannot integrate any plugin it seems.
Not all jQuery options are available with jqLite
angular.element used jqLite – which contains limited options – listed here. But, the jQuery plugin is attached with jQuery object which is separate from the jqLite object. To solve this issue, we need to include jQuery core in our application.
jQuery before or after Angular?
By the docs, I understand, if we include jQuery before Angular, there will be no issues. We can use any jQuery integrated Angular directive. But… the jqLite will be replaced by the jQuery object, that means the angular.element will be a jQuery object instead of jqLite object. I don’t want to to do this because this will decrease the performance of the application, imagine we are using so many elements in the application those are replaced by heavy object instead of simple. So, I included jQuery source after Angular source.
Converting angular.element to jQuery element
Now we have angular element and jQuery – but we need to get jQuery object from the Angular element. This we can get using $, when link is
Now we have angular element and jQuery – but we need to get jQuery object from the Angular element. This we can get using $, when link is
link: function link ($scope, $element, attrs, modelCtrl) {
Instead of
$element.intlTelInput;
we could use
$($element[0]).intlTelInput;
More tricks: jQuery object with ng-click
We can do more things using this trick. For example, if we want to do something with focus/blur with ng-click, with angular element, we cannot. But, by converting the element to jQuery object we will get all the jQuery options with the element (jQuery should be included after Angular source). If we have an element with ng-click
<button ng-click="focusFirst($event)">Focus First Input</button>
and want to focus an element within the same container, we could write
$scope.focusFirst = function(event) { var me = $(event.target); var container = me.closest('.container-class'); container.find('input').eq(0).focus(); };