I'm using node, gulp and browserify to get my JS-Files into the right order and manage modules. I have jQuery and AngularJS installed as node modules and require them when needed. Angular by default uses jqLite to handle DOM-Elements.
I know that when jQuery gets loaded before AngularJS, Angular will use jQuery instead of jqLite.
But how is it possible to get Angular to use jQuery when using browserify. Or: How may one require jQuery to angular?
Now I'm just doing var $ = require("jquery"); and use it when I need it. But I'd like to have an Angular that will natively give me jQuery methods when doing for example:
app.directive("dir", function () {
return {
link : function ($scope, $elem) {
var a = $elem.width();//jQuery methods currently not available here
}
};
});
What I actually need to do:
var jQuery = require("jquery");
app.directive("dir", function () {
return {
link : function ($scope, $elem) {
var jqElement = jQuery($elem);
var a = $jqElement.width();//jQuery methods are available here
}
};
});
You can use browserify-shim
npm install browserify-shim --save-dev
package.json
"browserify": {
"transform": ["browserify-shim"]
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js"
},
"browserify-shim": {
"jquery": "$",
"angular": {
"exports": "angular",
"depends": ["jquery"]
}
}
For AngualrJS 1.x use a value provider
var jQuery = require('jQuery');
var app = require('../app');
app.value('jQuery', jQuery);
Then in your Directives or Components where you need it (you shouldn't need jQuery):
var app = require('../app');
foo.$inject = ['jQuery'];
function foo(jQuery) {
return {
restrict: 'A',
scope: true,
link: function(element, scope, attr) {
// I can use jQuery here
// though I am unsure why
// I would want to.
}
}
}
app.directive('foo', foo);
Now if you need to write a Unit Test for this directive you can inject a stub for jQuery if need be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With