3

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?

jonhobbs
  • 26,684
  • 35
  • 115
  • 170

2 Answers2

2

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 2
    Thanks. Seems a shame to have to include the whole of jQuery, just to find the "shallowest" match on a selector. I might look into a pure JS way to do this. – jonhobbs Apr 20 '15 at 16:01
0

jQlite does not support jQuery plugins. In reality it is meant to be a light-weight selector tool -- not a heavy-weight tool that supports extending, like jQuery.

You have two options:

  1. Use JavaScript to implement the functionality ( element.getElementBySelector('foo)[0] ).
  2. Include jQuery in your project.

I would personally use option 1.

Martin
  • 15,820
  • 4
  • 47
  • 56