1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But how to? I define a controller "testCtrl" by using .controller() and then use controllerAs:'testCtrl'. then nothing happens.
/What are expecting after defining the controller?
Nothing happens means the controller that defined by .controller() cannot be assign to the directive by using controllerAs:'testCtrl'. when I console.log() the controller in link, it displays 'undefined'.
Hey @PandaYang, my assumption of controllerAs option was wrong. You can you the controller option directly. I've updated my answer and added a fiddle link to fix your problem.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.