What issues might I experience in having two different versions of AngularJS loaded into one page?
Obviously this seems like a stupid thing to do, but my use case is a page that uses AngularJS incorporating a third-party component that drags in its preferred version of AngularJS.
Update:
Found some info:
https://groups.google.com/forum/#!msg/angular/G8xPyD1F8d0/u1QNDNvcwW4J https://github.com/angular/angular.js/pull/1535
Only one ngApp directive can be auto-bootloaded per HTML Document but you can have multiple apps as long as you manually bootstrap the subsequent ones.
All AngularJS applications must have a root element. You can only have one ng-app directive in your HTML document.
And also mentioned in angular interview questions that "Only one AngularJS application can be auto-bootstrapped per HTML document." Which means that your page can only have single ng-app attribute.
Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.
Angular is really not prepared to co-exist with other version. But it's feasible.
First of all load angular library and make sure that before loading window.angular
is empty:
<script src="vendor/angular/1.2.0/angular.min.js"></script>
<script src="app/app2.js"></script>
<script>
var angular2 = angular;
window.angular = null; // here we're cleaning angular reference
</script>
<script src="vendor/angular/1.0.5/angular.js"></script>
<script src="app/app1.js"></script>
<script>
var angular1 = angular;
</script>
Note that each application (app1.js
, app2.js
) for each version of angular should be loaded immediately after loading angular library.
Each JavaScript file of the application shoud be wrapped in self executing function (function(angular) { ... })(angular)
. Look at the example of app2.js
:
(function(angular) {
angular.module('myApp2', []).
controller('App2Ctrl', function($scope) {
$scope.$watchCollection('[a, b, c]', function() {
console.log(angular.version.full);
});
});
})(angular);
Note that here I'm using $watchCollection
which is only available for angular 1.2.x. By providing scope of anonymous function for each file you are forcing application to reach angular
property instead of window.angular
property.
Finally you have to bootstrap the application using manuall method:
<body>
<div id="myApp1" ng-controller="App1Ctrl">
</div>
<div id="myApp2" ng-controller="App2Ctrl">
</div>
<script>
angular1.bootstrap(document.getElementById('myApp1'), ['myApp1']);
angular2.bootstrap(document.getElementById('myApp2'), ['myApp2']);
</script>
</body>
Working plunker here. After running please check console window to see logged versions of angular used.
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