Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force AngularJS to use specific version of jQuery while using multiple versions of jQuery at once

I inherited the project where several version of jQuery are loaded into the page in noConflict mode. Application is huge, tests are missing and it seems every former devloper did not have "cohones" big enough to remove previous library. So the result is that $ refers to jquery version 1.4.2.
Is there any way/trick to tell angular wich version of jQuery should be used? Something like

angular.jq = j182

I know I can do it like

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
 <script src="xxx/scripts/angular.js"></script>  
 <script>j182 = jQuery.noConflict();</script>

but then I have kind of "hidden dependency" which I would like to avoid.

like image 324
mrok Avatar asked Oct 21 '22 11:10

mrok


1 Answers

You're right that $.noConflict() allows you to play with 2 versions of jQuery at once (which should be avoided unless REALLY necessary).

To make your angular module use the version you want, you can use ng-jq="whateverYouCallIt" where whateverYouCallIt is variable in window. Example:

<script type="text/javascript" src="/js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">window.j190 = jQuery.noConflict();</script>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    console.log('globally available jQuery: ' + jQuery.fn.jquery);
    console.log('j190: ' + window.j190.fn.jquery);
</script>
...
<div ng-app='myApp' ng-jq="j190" ng-controller='MyController' id="myAngularApp">

Just be careful, because if you need to access $scope from somewhere else, you will have to obtain it via the same jQuery that has been specified in ng-jq:

var myAnguarAppScope = window.j190('#myAngularApp').scope();

BTW, the above console.log calls output:

globally available jQuery: 1.7.2
j190: 1.9.0

like image 56
LihO Avatar answered Oct 23 '22 06:10

LihO