Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Module Private Members

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>
like image 664
Michael Allan Jackson Avatar asked Jun 05 '13 21:06

Michael Allan Jackson


2 Answers

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.

like image 134
pkozlowski.opensource Avatar answered Sep 26 '22 05:09

pkozlowski.opensource


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.

like image 41
Ozymandias Avatar answered Sep 23 '22 05:09

Ozymandias