0

Because of the way my company's website was developed originally (ASP .NET w/ascx pages and codebehind), I have had to use Angular's manual bootstrap in order to get 2 Angular applications on the same page. 1 Application at any given time controls the main viewport that the user interacts with (this is the bulk of the application), while the other application is just a simple one for controlling our Header at the top of the page.

Since I wanted both areas of the site to use Angular, I was forced to use manual bootstrapping in order to bootstrap the Header application to the page.

This has worked great up until recently where I needed both sections of the page to act on the same factory, i.e. I want to show Alerts in the header application as well as the main application. When I attempted to do this I noticed that 2 instances of the factory were being instantiated. I could modify variables from one end and they would not persist from the other end.

My guess is that manually bootstrapping the header application causes a "disconnect" between the 2 apps and therefore result in the behavior I am noticing.

Does this sound correct? Or am I probably just doing something incorrect?

TL;DR

Can 2 AngularJS Applications share the same Angular factory singletons or do they each instantiate their own? My guess is that ngApp and angular.bootstrap both instantiate the root $rootScope and all child entities inherit from them. Therefore, in the case that you 2 apps and 2 $rootScopes, trying to add DOM events onto 1 will not propagate successfully to the other

Matt Hintzke
  • 7,744
  • 16
  • 55
  • 113

1 Answers1

0

Correct. An instance of injector is created per application, and each instance of the injector creates its own instances of the services.

Here's an easy illustration:

angular.module("foo", [])
  .factory("fooSvc", function(){
    return { val: Math.random() };
  });

angular.module('app1', ["foo"])
  .controller('App1Ctrl1', function($scope, fooSvc) {
    $scope.val = fooSvc.val; // 0.9966537940781564
  });

angular.module('app2', ["foo"])
  .controller('App1Ctrl2', function($scope, fooSvc) {
    $scope.val = fooSvc.val; // 0.6884669279679656
  });
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • wait.. so you can't even share services across modules? Can't you have multiple modules inside the same app that all use the same services? – Matt Hintzke Feb 06 '15 at 16:56
  • Yeah, but, inside the *same app*. The injector is created in the context of the app. The module of the `foo` service doesn't matter. There are [some ways](http://stackoverflow.com/a/16725874/968155) to create shareable services, but you really need to consider why you have 2 apps running side-by-side. – New Dev Feb 06 '15 at 17:45
  • @MattHintzke, did the answer address your question? – New Dev Feb 09 '15 at 14:51