Dynamic Page Title with AngularJS

Page title is the most common and important fact for a website as well as an application which influence the SEO score of a website. Generally, page title needs to change for each page depends on the page content. This article is for creating dynamic page title with AngularJS and ui-router.

At first, you need to download ui-router module and load in your application. Then configure your applications routes by using ui-router module.

Example of Dynamic Page Title with AngularJS:

app.config(function ($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/')

    $stateProvider.state('home', {
        url: '/',
        templateUrl: 'home.html',
        data: {
            title: 'Home Page'
        }
    });

    $stateProvider.state('about', {
        url: '/about',
        templateUrl: 'about.html',
        data: {
            title: 'About Me'
        }
    });

    $stateProvider.state('blog', {
        url: '/blog',
        templateUrl: 'blog.html',
        data: {
            title: 'Personal Blog'
        }
    });

    $stateProvider.state('contact', {
        url: '/contact',
        templateUrl: 'contact.html',
        data: {
            title: 'Contact Me'
        }
    });
});

From the above code snippet, you can see I have configured my routing by using ui-router. According to ui-router I have used $stateProvider.state to create my individual route. And I added the title for each state which I will show into the browser.

app.run(['$rootScope', '$state',
        function ($rootScope, $state) {
            $rootScope.$on('$stateChangeSuccess', function () {
                $rootScope.title = $state.current.data.title;
            });
        }
    ]
);

And this snippet of code will execute while angular application will run. With the $rootScope.$on getting the successfully state changes ($stateChangeSuccess) and taking the each state’s title and assign into $rootScope.title.

And then modify your title tag to include ng-bind:

<title ng-bind="(title || 'Home') + ' - AngularJS Dynamic Title'">
   AngularJS Dynamic Title
</title>

This is really simple and easy way to set Dynamic Page Title with AngularJS. Here I have included a demo and source code link for you. Hope these will be helpful for you.

Demo Link: https://sohelrana820.github.io/dynamic-page-title-with-angular-js/#/

Source Code: https://github.com/sohelrana820/dynamic-page-title-with-angular-js