5

I recently saw this example. It's the first time I have seen a controller inside a directive. Is this a normal thing to do. I thought you were supposed to keep these two in different areas for testability:

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
})
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • The `tabs` directive on the Angular home page (see Create Components, components.js tab) has a controller so that the `pane` directive can get access to the tabs' $scope (for more on this see http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers/14168699#14168699). See also [Difference between controller and link functions in a directive](http://stackoverflow.com/questions/12546945/difference-between-the-controller-and-link-functions-when-defining-an-angula/12570008#12570008). – Mark Rajcok Apr 06 '13 at 16:07

1 Answers1

5

Generally, you'd use controllers in directives to be able to share them between directives, on an element. It allows for directives to comunicate between them easily.

See here for a great explanation of how this works: http://egghead.io/video/angularjs-directive-to-directive-communication/

Tiago Roldão
  • 10,629
  • 3
  • 29
  • 28