Is it possible to apply multiple AngularJS controllers on the same element ?
An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application.
Multiple controllers can be used in a single html page, provided they all belong to the same module.
You can't inject controllers into one another.
The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.
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?
You could extend a controller and use it wherever you like. See the Fiddle for a better example.
<script>
var multiApp = angular.module('new', []);
multiApp.controller('aCtrl', ['$scope', '$controller', function ($scope, $controller) {
$scope.text1 = 'Hello';
angular.extend(this, $controller('bCtrl', {$scope: $scope}));
}]);
multiApp.controller('bCtrl', ['$scope', function ($scope) {
$scope.text2 = 'World!';
}]);
</script>
With html like:
<body ng-app="new">
<div id="container1" ng-controller="aCtrl">
{{text1}} {{text2}}
</div>
</body>
Fiddle: http://jsfiddle.net/kkelly/thk9n20o/#base.com
HTML is a form of XML, and it is not valid xml to have multiple non-unique attributes on the same element. In other words,
<div ng-controller="a" ng-controller="b">
is invalid. But what about when we do
<div id="a" ng-controller="a">
<div id="b" ng-controller="b">
<div id="c">
This is valid xml/HTML, but it is not assigning two controllers to the div
with id c
. This is called Nested Controllers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With