Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  78] [ 1]  / answers: 1 / hits: 44050  / 10 Years ago, fri, february 20, 2015, 12:00:00

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


More From » angularjs

 Answers
11

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?


[#67731] Thursday, February 19, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maurodannyr

Total Points: 126
Total Questions: 103
Total Answers: 105

Location: Maldives
Member since Sun, Feb 27, 2022
2 Years ago
;