Search code examples
javascriptjqueryangularjsjqlite

Angular JS - Adding a jquery plugin to jQlite


I need to do some dom traversal on a $element, but jQuery or jQlite don't do what I need out of the box so I need to use a jQuery plugin called closestChild.

https://github.com/lolmaus/jquery.closestchild/blob/master/jquery.closestchild.js

I have installed using bower and I'm trying to load it after angular.min.js in my script tags but still getting the following error.

Uncaught TypeError: Cannot read property 'fn' of undefined

So, I assume that jQlite that comes with Angular doesn't give you the $ to work with by default? Or am I just doing things in the wrong order?


Solution

  • No, angular.element (jqLite) doesn't export $ global variable. So you can't just use any jQuery plugin with Angular without jQuery. In some cases, you can workaround it if you manually create $ reference before including plugin like if it was jQuery. For example like this:

    <script src="path-to-angular.js"></script>
    <script>
    window.$ = window.jQuery = angular.element;
    window.$.fn = window.$.prototype;
    </script>
    <script src="path-to-jquery.plugin.js"></script>
    

    However, in your case it will not work, because the plugin of interest uses $.fn.filter method, which jqLite doesn't implement. Here is the list of all available angular.element methods.

    You can implement some of them by yourself and include before plugin..

    However, I would recommend to actually use jQuery if you want to use jQuery plugins.