Click here to Skip to main content
15,867,851 members
Articles / AngularJs

Change the Page Title Dynamically Using Angular JS

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
8 Mar 2016CPOL3 min read 15.5K   2   5
How to change the title of a page dynamically using Angular JS

In this article, we are going to see how we can change the title of a page dynamically using Angular JS. We will be showing random titles which we have already set in an array to the user whenever user reloads the same page. To implement this, we are creating angular js controller and service. And we are treating the html tag of our page as our angular js app module and controller. Now shall we go and see this in detail? I hope you will like this.

Background

For the past few days, I am just doing some experiments with Angular JS. If you want to see my latest articles related to Angular JS, please take a look here: Angular JS Latest Articles . Here in this post, we are going to change the page title dynamically in each user actions. I hope you all know how important a title tag is in a page. Let us take a look at that first.

Importance Of Title Tag

  • A title tag add title in browser toolbar
  • It also provides title for the pages when the page is added to favorites
  • Positively affect your page ranking in Google search, by displaying title for the page in search result

Now we will start our coding. I hope you will enjoy reading.

Create an Empty Website in Visual Studio

Click File-> New-> Web Site.

Empty Website In Visual Studio

Empty Website In Visual Studio

Install Angular JS from NuGet Packages

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

Install Angular JS From NuGet Packages

Install Angular JS From NuGet Packages

Now create a new page, start coding.

Using the Code

Before starting, we need to add the needed references to our page, right?

HTML
<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:

HTML
<!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. Are you ready?

Add Angular JS App

You can add an angular js app as follows:

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

Now we will create our controller.

Add Angular JS Controller

Below is our Angular JS controller scripts.

JavaScript
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 Angular JS service name, and as you can see, we have set an array with possible tiles in it already. We are generating one random number between 1 to 6 and take the appropriate value from the array by index. You can always load these 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

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

Now let us see the complete Angular JS scripts.

Complete Scripts

JavaScript
(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 that is needed. Now, it is time to see the output.

Output

Chnage_Page_Title_Dynamically_Using_Angular_JS_Output

Chnage_Page_Title_Dynamically_Using_Angular_JS_Output

Chnage_Page_Title_Dynamically_Using_Angular_JS_Output

Chnage_Page_Title_Dynamically_Using_Angular_JS_Output

Happy coding!

Conclusion

Did I miss anything that you may think is needed? Have you ever wanted to do this requirement? Could you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback.

Your Turn. What Do You think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
QuestionWrong type Pin
Richard MacCutchan8-Mar-16 0:08
mveRichard MacCutchan8-Mar-16 0:08 
AnswerRe: Wrong type Pin
Sibeesh Passion8-Mar-16 0:21
professionalSibeesh Passion8-Mar-16 0:21 
GeneralRe: Wrong type Pin
Richard MacCutchan8-Mar-16 0:28
mveRichard MacCutchan8-Mar-16 0:28 
AnswerRe: Wrong type Pin
Sibeesh Passion8-Mar-16 0:29
professionalSibeesh Passion8-Mar-16 0:29 
Questionitalic Pin
Nelek7-Mar-16 22:47
protectorNelek7-Mar-16 22:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.