Angular custom directive with multiple controller

 

In this example, we are creating a directive and will use that in multiple controller and pass the page-title value from different controller. See the example:

 
 
 
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <body ng-app="Example" class="container"> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#student">Students</a></li> <li><a href="#teacher">Library</a></li> <li><a href="#library">Teachers</a></li> </ul> </div> <div ng-controller="studentController" id="student"> <page-header page-title="pageTitle"></page-header> </div> <div ng-controller="teacherController" id="teacher"> <page-header page-title="pageTitle"></page-header> </div> <div ng-controller="libraryController" id="library"> <page-header page-title="pageTitle"></page-header> </div> </body> </html> <script> angular.module('Example', []) .controller('studentController', function ($scope) { $scope.pageTitle = "Student Detail"; }).controller('libraryController', function ($scope) { $scope.pageTitle = "Library Detail"; }).controller('teacherController', function ($scope) { $scope.pageTitle = "Teacher Detail"; }).directive("pageHeader", function () { return { restrict: 'E', pageTitle: '=', template: '<div class="jumbotron container"><h3>{{pageTitle}}</h3></div>' } }) </script> <script src="pageHeader.js"></script>
Output