As you know, when you are using the routing functionality with Angular, then you always have just one title element. This title be updated dynamically with the correct title text.

There are surely several ways to do that, I will show you 2 ways how you can do that.

 

Option 1

Option 1 sets the title in the routing information and we are going to read that information with an event when the routing was successful.

First, lets define our routes in our app.js file

You see here, we added a new attribute title to it. We can define here which title should be used for the page.

Now, lets hook on the $routeChangeSuccess event to set a pageTitle scope like this:

So, you are now able to add the ng-Controller to the head and use the pageTitle

Thats it. It is a simple and easy way to do it.

 

Option 2

The second option is, we are defining a service and setting it up in each controller.

First, lets create our service:

Now lets create in our AppCtrl our scope to be usable everywhere:

then lets set the pageTitle in our MainController:

and finally, lets call our service from our html:

so, thats it. let me know which one do you prefere and if you have another way of doing it.

Change title element in AngularJS dynamically
Tagged on:

2 thoughts on “Change title element in AngularJS dynamically

  • December 11, 2015 at 4:49 pm
    Permalink

    It’s wrong here : setTitle: function (newTitle) { title = newTitle; }

    You need add return as well. Other wise, you will get “undefine”

    Sample:

    setTitle: function (newTitle) { return title = newTitle; }

    Correct me if I’m wrong.

    Reply
    • January 26, 2016 at 8:04 am
      Permalink

      Yeah, I think we are both right.. since I am using then the title, not the return value of the setTitle, it works. I am setting a new title, and consuming it from title, not from setTitle.. If you would like to use it immediately, then I think you are right, you will need a return value.. but in my case how I am using it, it is not necessary.

      Reply

Leave a Reply

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: