How to use two or more controllers in one page with AngularJS

In this tutorial I will explain how is possible to use two or more controllers in one page with AngularJS.

I will create a simple AngularJS controller:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="New">
{{message}}
</div>
<script language="javascript">
function New($scope)
{
$scope.message = "New message!";
}
</script>
</body>
</html>

To use a new controller in this same page, you must only move ng-app from div to body: <body ng-app>

Then you will be able to use multiple controllers:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app>
<div ng-controller="New">
{{message}}
</div>
<div ng-controller="New2">
{{message}}
</div>
<script language="javascript">
function New($scope)
{
$scope.message = "New message!";
}
function New2($scope)
{
$scope.message = "New message!";
}
</script>
</body>
</html>

In this way you can use multiple controllers in a single page!









Leave a Comment