Dynamically Change Page Header In AngularJS

Posted by Weston Ganger on July 17, 2015

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">
    <title ng-bind="PageHeader.pageTitle()"></title>

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

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

Posted in Angular and Tagged with angularjs 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts