Angular Module Members

In AngularJS, you can create private controllers or services that can be used in the module in which they are defined, but not with the help of another module into which they are inserted.

For example, privateController may be private to the Child module:

angular.module('Child', []) .controller('PublicController', function ($scope){ $scope.children = ['Bob', 'Sue']; }) .controller('PrivateController',function ($scope){ $scope.redHeadedStepChildren = ['Billy', 'Mildred']; }) angular.module('Parent', ['Child']) 
 <div ng-app="Parent"> <div ng-controller='PublicController'> <div ng-repeat='child in children'> {{child}} </div> </div> <div ng-controller='PrivateController'> <div ng-repeat='child in redHeadedStepChildren'> {{child}} </div> </div> </div> 
+6
source share
2 answers

No , it is not possible to create "private" services in the current version of AngularJS. There were some discussions about supporting private (modular) services, but they were not implemented.

Today, all services exposed on this module are visible to all other modules.

+5
source

For the true behavior of a private decorator, @ pkozlowski.opensource has the correct answer No. However, you could simulate this behavior.

One way to get closer to the desired behavior is to create a module that is unknown to all other parts of the application, which contains all the services / controllers / directives that should remain closed. Then the module that you will expose to other developers can use the "private" module as a dependency.

Example:

Mymodule.js

 angular.module("my.module.private_members", []) .provider("PrivateService", function() { ... }); angular.module("my.module", ["my.module.private_members"]) .provider("PublicService", function($PrivateServiceProvider) { ... }); 

Main.js

 angular.module("app", ["my.module"]) // The following line will work. .config(function($PublicServiceProvider) { ... }); // The following line causes an error .config(function($PrivateServiceProvider) { ... }); 

Of course, this will not work if the developer of the "app" module finds out that he then includes the module "my.module.private_members" as a direct dependency of the "app" module.

This example should apply to controllers.

0
source

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


All Articles