Dynamically Change Page Header In AngularJS

Posted By Weston Ganger

Changing the page header as the route changes is important. You will probably want to set the page title and meta tags.

Were going to create a service that you can include in your controllers to use. Add or Remove to the service as you desire.

.service('PageHeader', function() {
  var pageTitle = 'My App';
  var metaDescription = '';
  var metaKeywords = '';
  return {
    pageTitle: function() { return pageTitle; },
    metaDescription: function() { return metaDescription; },
    metaKeywords: function() { return metaKeywords; },
    reset: function() {
      pageTitle = 'My App';
      metaDescription = '';
      metaKeywords = '';
    },
    setPageTitle: function(newPageTitle) {
      pageTitle = newPageTitle;
    },
    setMetaDescription: function(newMetaDescription) {
      metaDescription = newMetaDescription;
    },
    appendMetaKeywords: function(newKeywords) {
      for (var key in newKeywords) {
        if (metaKeywords === '') {
          metaKeywords += newKeywords[key].name;
        } else {
          metaKeywords += ', ' + newKeywords[key].name;
        }
      }
    }
  };
});

To use it make sure your layout is setup as follows:

<pre><code class='language-markup'>
<html ng-app="myApp" ng-controller="myCtrl">
<head>
<title ng-bind="PageHeader.pageTitle()"></title>

<meta name="description" content="{{ PageHeader.metaDescription() }}">
<meta name="keywords" content="{{ PageHeader.metaKeywords() }}">
</head>
<body>
</body>
</html>


Now you can include the service in your controllers and change it based on the information.

Article Topic:Software Development - Javascript

Date:July 17, 2015