Why can 2 different modules contact each other when added depending on the third module?

I have 3 modules in my AngularJS application, for example. main , home and product . main with home and product modules as dependencies ( ng.module('main', ['home', 'product']) ), while home and product modules have no dependencies ( ng.module('product', []) ng.module('phome', []) ), can the product module access the module's home service? WHY???

Below is a sample code of my application that has the same script and the same problem. And this is the JSfiddle link .

 <!DOCTYPE html> <html ng-app="main"> <body ng-controller="MainController as mainController"> {{mainController.name}} <script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <script> (function (ng) { var homeModule = ng.module('home', []); homeModule.service("HomeService", [function () { var homeService = this; homeService.getName = function () { return "Home Service"; } }]); var productModule = ng.module('product', []); productModule.service("ProductService", ["HomeService", function (HomeService) { var productService = this; productService.getName = function () { return "Product Service - " + HomeService.getName(); }; }]); var mainModule = ng.module('main', ['home', 'product']); mainModule.controller("MainController", ['ProductService', function (ProductService) { var mainController = this; mainController.name = ProductService.getName(); }]); })(angular); </script> </body> </html> 
+6
source share
2 answers

The answer is pretty simple. Angular does not extend the contents of the module to the module itself. I read somewhere that there were discussions of adding this function, but I have not yet seen it implemented.

To make matters worse, the controllers applied to a single imported module will be unique in your application. As an example, I once used angular -ui bootstrap, and someone from my team added AlertController . We were very confused when the controller never hit, but that was because angular -ui already defined the controller.

Thus, it is not just a matter of visibility, but also maintainability and naming.

Everything that is defined in the module is publicly available.

+3
source

This works because the dependency of the home module is added to the main module, and since main calls only the product service , so it should depend only on the product module.

If you remove the dependency form of the home module on the main module (which should be so), it stops working.

TL; DR ; The downside of not adding the home module to the product module is that it does not work, only adding the product dependency, but you need to add the home dependency and also work with the product service .

jsfiddle

0
source

Source: https://habr.com/ru/post/988305/


All Articles