Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Change Page Titles Dynamically Using AngularJS

DZone's Guide to

Change Page Titles Dynamically Using AngularJS

In this article, we are going to see how we can change the title of a page dynamically using AngularJS. Read on and see how it's done.

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

In this article, we are going to see how we can change the title of a page dynamically using AngularJS. We will be showing random titles which we have already set in an array to the user whenever a user reloads the same page. To implement this, we are creating an AngularJS controller and service, and we are treating the HTML tag of our page as our AngularJS app module and controller. 

You can always download the source code here: Change The Page Title Dynamically

Background

For the past few days, I have been experimenting with AngularJS. If you want to see my latest articles related to Angular JS, they are here: Angular JS Latest Articles . In this post, we are going to change the page title dynamically with each user action. 

Importance of Title Tag

  • A title tag adds the title in a browser toolbar
  • It also provides a title for the page when added to favorites
  • You can also positively affect your page ranking in Google search by displaying title for the page in search result
  • Now we will start coding.

    Create an Empty Website in Visual Studio

    Click File-> New-> Web Site.

    Image title

    Empty Website In Visual Studio

    Install AngularJS from NuGet Packages

    Once your application is opened, please install AngularJS first, since we are going to do all of our coding using AngularJS.

    Image title

    Install Angular JS From NuGet Packages

    Using the Code

    Before starting, we need to add the necessary references to our page.

    <script src="Scripts/angular.min.js"></script>
        <script src="Scripts/angular-aria.min.js"></script>
        <script src="Scripts/angular-route.min.js"></script>
        <script src="Scripts/myScripts.js"></script>

    Here "myScripts.js" is our JavaScript file where we are going to write out Angular JS scripts. Once you add the reference, we will make some changes in our page as follows.

    <!DOCTYPE html>
    <html ng-app="titApp" ng-controller="titCtrl as t">
    <head>
        <title>{{t.title}} - Sibeesh Passion</title>
    
        <meta charset="utf-8" />
        <script src="Scripts/angular.min.js"></script>
        <script src="Scripts/angular-aria.min.js"></script>
        <script src="Scripts/angular-route.min.js"></script>
        <script src="Scripts/myScripts.js"></script>
    </head>
    <body>
        <h1>{{t.title}}</h1>
    </body>
    </html>

    As you can see, titApp is our Angular JS app name and titCtrl is our controller name, now we will start writing the scripts. 

    Add Angular JS App

    You can add an Angular JS app as follows.

    (function () {
        var app;
        app = angular.module('titApp', []);
    })();

    Now we will create our controller.

    Add Angular JS Controller

    Below is our Angular JS controller scripts.

    app.controller('titCtrl', function ($scope, myFactory) {
            var num = Math.floor(Math.random() * 6) + 1;
            var newTit = ['Change Page Layout Dynamically Using jQuery Layout Plug in', 'February 2016 Month Winner In C-Sharp Corner',
            'Custom Deferred Grid Using MVC Web API And Angular JS', 'TagIt Control With Data From Database Using Angular JS In MVC Web API',
            'jQuery Datatable With Server Side Data', 'Programmatically Extract or Unzip Zip,Rar Files And Check'];
            myFactory.setTitle(newTit[num]);
            var tt = myFactory.getTitle();
            if (tt != undefined) {
                this.title = tt;
            } else {
                console.log('Oops! Something went wrong while fetching the data.');
            }
        });

    Here myFactory is our AngularJS service name, and as you can see we have set an array with possible titles. We are generating one random number between 1 and 6 and take the appropriate value from the array by index. You can always load the data from a database instead. Here we use two functions setTitle and getTitle, to set the title and get the title. Now we will see our Angular JS service scripts.

    Add Angular JS Service

    app.service('myFactory', function () {
            var varTitle = 'Change Title Dynamically Demo';
            this.getTitle = function () {
                return varTitle;
            };
            this.setTitle = function (tit) {
                varTitle = tit;
            };
        });

    Now, let's see the complete Angular JS scripts.

    Complete Scripts

    (function () {
        var app;
        app = angular.module('titApp', []);
        app.controller('titCtrl', function ($scope, myFactory) {
            var num = Math.floor(Math.random() * 6) + 1;
            var newTit = ['Change Page Layout Dynamically Using jQuery Layout Plug in', 'February 2016 Month Winner In C-Sharp Corner',
            'Custom Deferred Grid Using MVC Web API And Angular JS', 'TagIt Control With Data From Database Using Angular JS In MVC Web API',
            'jQuery Datatable With Server Side Data', 'Programmatically Extract or Unzip Zip,Rar Files And Check'];
            myFactory.setTitle(newTit[num]);
            var tt = myFactory.getTitle();
            if (tt != undefined) {
                this.title = tt;
            } else {
                console.log('Oops! Something went wrong while fetching the data.');
            }
        });
        app.service('myFactory', function () {
            var varTitle = 'Change Title Dynamically Demo';
            this.getTitle = function () {
                return varTitle;
            };
            this.setTitle = function (tit) {
                varTitle = tit;
            };
        });
    })();

    We have done everything needed, Now it is time to see the output.

    Output

    Chnage_Page_Title_Dynamically_Using_Angular_JS_Output


    Change_Page_Title_Dynamically_Using_Angular_JS_Output


    Chnage_Page_Title_Dynamically_Using_Angular_JS_Output


    Change_Page_Title_Dynamically_Using_Angular_JS_Output


    Happy coding!

    Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

    Topics:
    angularjs

    Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    THE DZONE NEWSLETTER

    Dev Resources & Solutions Straight to Your Inbox

    Thanks for subscribing!

    Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

    X

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}