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

久未见 提交于 2019-12-10 14:13:46

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/22598106/force-angularjs-to-use-specific-version-of-jquery-while-using-multiple-versions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!