In AngularJS, is it possible to create private controllers or services which can be used within the module they are defined in, but not by another module they are injected into.
For example, can PrivateController be made 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>
No, it is not possible to create "private" services in the current version of AngularJS. There were some discussions about support for private (module-scoped) services but it is not implemented.
As of today all the services exposed on a given module are visible to all other modules.
For true private decorator behavior, @pkozlowski.opensource has the correct answer of No. However, you could somewhat simulate this behavior.
One way to get close to the desired behavior is to create a module which is unknown to all other parts of the application, which contains all services/controllers/directives that are meant to remain private. Then the module you will be exposing 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 does not work if the developer of the "app"
module becomes aware of then includes the "my.module.private_members"
module as a direct dependency of the "app"
module.
This example should extend to controllers.
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