Great question!
So, this is a common problem not only with the controllers, but also potentially with the services that the directive may require in order to carry out its work, but do not necessarily want to expose this controller / service to the “outside world”.
I strongly believe that global data is evil and should be avoided, and this also applies to directory controllers . If we accept this assumption, we can use several different approaches to define these controllers “locally”. In this case, we need to keep in mind that the controller should be "easily" available for unit tests , so we can not just hide it in a directory closure. IMO features:
1) First, we could just define a directory controller at the module level , ex ::
angular.module('ui.bootstrap.tabs', []) .controller('TabsController', ['$scope', '$element', function($scope, $element) { ... }]) .directive('tabs', function() { return { restrict: 'EA', transclude: true, scope: {}, controller: 'TabsController', templateUrl: 'template/tabs/tabs.html', replace: true }; })
This is a simple method that we use at https://github.com/angular-ui/bootstrap/blob/master/src/tabs/tabs.js , which is based on the work of Vojta.
Although this is a very simple method, it should be noted that the controller is still exposed to the entire application, which means that another module can potentially override it. In this sense, the controller localizes the AngularJS application (therefore, it does not pollute the global area of the window), but also globally for all AngularJS modules.
2) Use the closing area and special files for testing .
If we want to completely hide the controller function, we can wrap the code in closure. This is the method that uses AngularJS. For example, looking at the NgModelController , we see that it is defined as a “global” function in its own files (and, therefore, is easily accessible for testing), but the entire file is closed during the build time:
To summarize: option (2) is “more secure”, but a bit of pre-configuration is required for assembly.