Code


<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="script.js"></script> </head> <body ng-app> <div ng-controller="firstController"> <h2>Model managed by the first controller</h2> <strong>First name:</strong> {{firstName}}<br /> <strong>Last name:</strong> <span ng-bind="lastName"></span><br /> <strong>Full name:</strong> {{getFullName()}}<br /> <br /> <label>Set the first name: <input type="text" ng-model="firstName"/></label><br /> <label>Set the last name: <input type="text" ng-model="lastName"/></label> </div> <div ng-controller="secondController"> <h2>Model managed by the second controller</h2> <strong>First name:</strong> {{firstName}}<br /> <strong>Middle name:</strong> {{middleName}}<br /> <strong>Last name:</strong> <span ng-bind="lastName"></span><br /> <strong>Full name:</strong> {{getFullName()}}<br /> <br /> <label>Set the first name: <input type="text" ng-model="firstName"/></label><br /> <label>Set the middle name: <input type="text" ng-model="middleName"/></label><br /> <label>Set the last name: <input type="text" ng-model="lastName"/></label> </div> </body> </html>
var firstController = function ($scope) { // Initialize the model variables $scope.firstName = "John"; $scope.lastName = "Doe"; // Define utility functions $scope.getFullName = function () { return $scope.firstName + " " + $scope.lastName; }; }; var secondController = function ($scope) { // Initialize the model variables $scope.firstName = "Bob"; $scope.middleName = "Al"; $scope.lastName = "Smith"; // Define utility functions $scope.getFullName = function () { return $scope.firstName + " " + $scope.middleName + " " + $scope.lastName; }; };

Example


Description


We can define multiple controllers in the same HTML template and each one manages its own $scope object.

In the example we have two controllers, firstController and secondController, and even though there are some model variables named in the same way for both the controllers, each one resides in its own $scope thus avoiding any conflict (they are in fact different variables even though the name is the same).