How to use jQuery and its modules with AngularJS ng-include

Hi, folks!
These days I’ve tried to convert a basic html template bought from codecanyon to AngularJS. But there was a problem.
The jQuery does not wait for AngularJS to load because.. asynchronicity of the JavaScript language.

After few discussions with Radu Amarie, the Head Of Engineering at Findie (a great start-up 😀 ) and few unsuccessful tests, he recommended me to try this function from SitePoint which I have inserted in my main Angular controller:


(function () {

function loadScript(url, callback) {

var script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

//jQuery loaded
console.log('jquery loaded');

});
})();

 

In the first place, the solution won’t worked, because the scripts was still loading asyncronously. After that, I have setted

async=false;

after

script.type = "text/javascript";

and magically jQuery and Angular became friends and now I can continue the work! 😀

 

Later edit:
I found that ocLazyLoad is a more elegant solution, in combination with directives. 🙂

 

Silviu Stroe
I'm Silviu and I run Brainic, a mobile-focused software agency. I'm also a member of Nokia and Yahoo wall of fame. My interests are in low-code/no-code development and bleeding-edge technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *