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:


<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 - Angular

Date:July 17, 2015

Recommended Posts