Heather Roberts
Heather Roberts

Reputation: 2148

How to make Angular use jQuery over jqLite

In my project I am using both jQuery and angular. I have installed these through bower and I am using browserify to load the files. This seems to work fine, except angular is using jqLite it seems. When I am trying to run

angular.element(".workItem").hide();

I get an error saying jqLite does not support query selectors. How can I get around this and make angular use jQuery?

I want to use angular.element over $ for testing purposes.

Thanks!

Upvotes: 3

Views: 2455

Answers (3)

Dansp
Dansp

Reputation: 1745

With are you using bower, go to your file bower.json and put jquery before any angular library into dependencies.

{
  "name": "myadmin",
  "version": "1.0.0",
  "dependencies": {
    "jquery": "~2.1.4",
    "angular-animate": "~1.6.9",
    "angular-cookies": "~1.6.9",
    "angular-touch": "~1.6.9",
    "angular-sanitize": "^1.6.9",
    "angular-messages": "~1.6.9",
    "angular-aria": "~1.6.9",
    "angular-resource": "~1.6.9",
    "angular-ui-router": "~0.4.0",
    "angular-bootstrap": "~2.4.0",
    "angular-toastr": "^2.1.1",
    "animate.css": "~3.4.0",
    "angular": "~1.7.0",
    ...

Upvotes: 0

benek
benek

Reputation: 2178

For make it working with browserify you have to require it : Add the jquery dependency to bower and do in your main file :

require('jquery');
global.jQuery = require('jquery');
global.$ = jQuery;

Until here, it is not visible by browserify because the reference is only in bower. So use browserify-shim to make the glue:

  • Install browserify-shim
  • In your package.json, add :
 "browserify": {
   "transform": [
     "browserify-shim"
   ]
 },
  "browser": {
    "jquery": "./bower_components/jquery/dist/jquery.js"

See https://github.com/thlorenz/browserify-shim for complete information.

Upvotes: 1

Adam Zerner
Adam Zerner

Reputation: 19248

From the docs:

To use jQuery, simply ensure it is loaded before the angular.js file.

So in your index.html file, you'll want something like this:

<html>
  <head>
    <script src='jquery.js'></script>
    <script src='angular.js'></script>
  </head>
</html>

After doing so, angular.element should work as a substitute for $:

If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."

Ie. angular.element('.foo') would be the same as $('.foo').

Upvotes: 4

Related Questions