Published on

How to Create Simple Header Directive in AngularJS

Authors

Header section will most probably come on every page in the app. We can have it as a partial file and include it in the page using ng-include or even hard code them in index page itself.

It works fine as long as you don't need much more functionalities like login/register in it.

So its good idea to have a separate directive for the header.

In my case, I've directive and its controller in the same file itself.

function headerDirective() {
  return {
    bindToController: true,
    controller: HeaderController,
    controllerAs: 'vm',
    restrict: 'EA',
    scope: {
      controller: '=',
    },
    templateUrl: 'app/header.tpl.html',
  };

  function HeaderController($scope) {
    console.log('Header is loaded');
  }
}

angular.module('directives.header', []).directive('header', headerDirective);

And on the index page, we have to call the directive.

<div header></div>

Don't forget to have to inject the module name.