faressoft faressoft - 4 months ago 26
Javascript Question

Is it possible to apply multiple AngularJS controllers on the same element

Is it possible to apply multiple AngularJS controllers on the same element ?

Answer

No, you cannot apply two controllers to the same element, but you can apply multiple directives. And directives can have controllers.

app.directive('myDirective1', function() {
return {
controller: function(scope) {
  //directive controller
  }
 };
});

app.directive('myDirective2', function() {
return {
controller: function(scope) {
  //directive controller
  }
 };
});

and in the HTML:

<div myDirective1 myDirective2></div>

And as mentioned in the comments below, the two controllers could share the same scope, which is often the desired effect; one of the two controller can request a new scope, but you cannot have two new scopes;

the reason for not allowing two isolated scope on the two directives, is that the view would not know where to get the scope values from, if a scope variable had the same name in the two isolated directive controllers

Here is an interesting read: Why can't multiple directives ask for an isolated scope on the same element?