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

Silviu is a full stack developer and entrepreneur. He is the founder of one of the first VPN services in Romania, RoTunneling and is part of Yahoo - Wall of Fame. He also loves bleeding edge technologies and new challenges.

No Comments


You can leave the first : )



Leave a Reply

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