angular custom directive example

 

In this example, we are using directive for creating left menu and this is a Html Element type of directive. The directive name is LeftMenu and are sending array of string item(items of leftMenu) and these types of items form different pages according to our requirement. 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"> <h3>Students</h3> <left-menu list-ltem="listItem"></left-menu> </div> <div ng-controller="teacherController" id="teacher"> <h3>Staff</h3> <left-menu list-ltem="listItem"></left-menu> </div> <div ng-controller="libraryController" id="library"> <h3>Library</h3> <left-menu list-ltem="listItem"></left-menu> </div> </body> </html> <script> angular.module('Example', []) .controller('studentController', function ($scope) { $scope.listItem = ["Student Detail", "Student Contact", "Student Marks"]; }).controller('libraryController', function ($scope) { $scope.listItem = ["Teacher Detail", "Teacher Contact", "Teacher lacture"]; }).controller('teacherController', function ($scope) { $scope.listItem = ["library Detail", "Books Detail", "Library Contact"]; }).directive("leftMenu", function () { return { restrict: 'E', listItem: '=', template: '<ul><li ng-repeat="i in listItem">{{i}}</li></ul>', } }) </script>
Output