panda
panda

Reputation: 1344

Directive controller vs. module.controller

I have been working a while in angular directive, for now, I came out with a problem.

What is the different between module.controller and the controller that could be defined in directive?

angular.module().controller()

angular.module().directive(function(){
   return {
     controller:
   }
});

The definition of both of them seems the same.

Another question is, would I assign the controller that defined by angular.module().controller() for directive controller?

Upvotes: 1

Views: 1025

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

Basically the functionality of both these controllers is essentially the same except that there is difference in the scope they act upon. Scope of the controller defined by the directive only applies to the element & children of that element, where the directive has been applied. Whereas controllers defined by the module act on scope of all elements where controller is defined with ng-controller.

Directive can also make use of the controller defined by angular.module(). This is achieved using controller key in the directive and providing the name of the module controller as a string.

Have a look at this example.

Upvotes: 2

Michael Kang
Michael Kang

Reputation: 52867

Module controllers are used to initialize scope on the hosting page. The scope on the hosting page relies on prototypical scope inheritance in a parent-child relationship.

Directive controllers are used to initialize scope for the directive's scope, which can be one of two types:

   1. Isolated scope
   2. Child scope (prototypical)

They are similar in that both kinds of controllers are used for initialization of scope. They are different in that each initialize their respective scopes: module controllers initialize page scope, directive controllers initialize the directive's scope.

The logic within a module controller is usually application specific but the logic within a directive controller is usually application-agnostic. Directive's are intended to be reusable, but application controllers are not.

Upvotes: 0

Related Questions