Maurizio Napoleoni's blog

Posted Sun 03 November 2013

Setting Page titles with AngularJS

Factories

In AngularJS if we want to share informations across multiple controllers we should use factories.

I needed to change the page titles from multiple locations, so I made use of an extremely simple factory. We are going to use a local variable, named title which contains the title, and two exposed methods: title, which is going to be in charge of returning the title, and setTitle which we'll call from the controllers to change the title page.

Here is our factory:

    angular.module('application.factories', [])
        .factory('PageTitle', function() {
            var title = 'Default title',
                separator = ' | ',
                suffix = 'Maurizio Napoleoni';

            return {
                title: function() {
                    return title;
                },
                setTitle: function(newTitle) {
                    title = newTitle + separator + suffix;
                }
            }
        })

Now let's have a look at our header: we have a specific controller for this part of the page, in charge of any change needed in it. In our case it controls the title of the page. One important thing: since the title of the page is going to be managed through angular, when the page loads first, our users would end up seeing PageTitle.title() before AngularJS loads, which is not really nice. To avoid that we make use of ng-bind, which once AngularJS is loaded will change the title to a more appropriate one.

    <html ng-app="application" ng-controller="MainCtrl" lang="en" class="no-js">
        <head>
            <title ng-bind="PageTitle.title()">Default title before AngularJS is loaded</title>

And in the MainCtrl and all the subsequent controllers we can inject the PageTitle factory.

    angular.module('application.controllers', [])
        .controller('MainCtrl', ['$scope', 'PageTitle', function($scope, PageTitle) {
            $scope.PageTitle = PageTitle;
        }]);
Category: JavaScript
Tags: angularjs angular factory

Comments