Although I am still new to Angular, I have been striving to write more modular code and rely less on cramming logic into the controller. Instead, I have been utilizing independent services. However, a recurring issue I am facing is having to re-declare the parent module multiple times. This leads to conflicts when downstream declarations have different dependencies injected compared to earlier ones.
Here is a simplified example of my current approach:
<body ng-app="myApp">
//first instance of "myApp" for some controller
var myApp = angular.module('myApp', ['dep1', 'dep2']);
var someCtrl = myApp.controller('someCtrl', ['dep3','dep4']);
//later... another instance of "myApp" for another controller
if (!myApp)
var myApp = angular.module('myApp', ['dep2']);
var anotherCtrl = myApp.controller('anotherCtrl', ['dep3','dep4']);
While this may seem simple in this example, the project I am working on is a large MVC PHP app with numerous reusable partials where it's not guaranteed that "someCtrl" will always be included before "anotherCtrl". Therefore, each module needs to be self-contained, and controllers/services cannot be declared unless they are attached to the parent "myApp".
I understand that dynamically (re)-injecting dependencies into a module later is not possible:
myApp.addDependancy(['dep7', 'dep8'])
The only solution I can currently think of is declaring "myApp" just once in the <head>
with every possible dependency from any potential controllers/services...
var myApp = angular.module('myApp', ['dep1', 'dep2', 'dep3' ... ]);
...and never re-declaring it. While this would simplify managing different dependencies, it does raise concerns about injecting unnecessary dependencies, potentially undermining the purpose of dependency injection.
Am I misunderstanding how this is supposed to work? What is the correct approach to handling this situation? Any links to documentation or resources would be greatly appreciated.
NOTE: I have come across information suggesting that overusing the same parent module ("myApp") is a common mistake in Angular. However, I need all controllers/services to communicate with each other using $rootScope, $watch, etc., so I believe they must all extend "myApp", right?