How to set or update page title using UI-Router?
UI-Router: UI-Router is a client-side router. It is made for single-page web applications. A client-side router updates the browser URL as the user navigates through the single-page app.
AngularJS allows you to change your page title at different stages
Let’s see how to change title
using a resolve function in our $state to tell the title
using $rootScope.$on(…) function within our module .run
by updating the title in our controller, good for dynamic page titles, like blog posts, etc.
This is the way you can set page title using UI-Router
Using Resolve:
Install angular-ui-title and append to your Angular project as usual, then don’t forget to inject the ui-router-title in your parent app module.
angular.module( 'codeSide' , [
'ui.router' , 'ui.router.title' ])
.config([ '$stateProvider' ,
'$urlRouterProvider' ,
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state( 'home' , {
url: '/' ,
templateUrl: 'home/home.html' ,
controller: 'HomeController' ,
resolve: function () {
$title: 'Homepage'
}
})
.....
)]);
|
In your Index file code should be
< head >
< title ng-bind =
"($title || 'Home') + ' :: CodeBySide'" >
CodeBySide
</ title >
</ head >
About US
Services
Contact US
< head >
< title ng-bind =
"($title || 'Home') + ' :: CodeBySide'" >
CodeBySide
</ title >
</ head >
|
Output:
our title is not dynamically generated in the above code.
Get titles to be dynamically generated
angular-ui-router changes the $rootScope to make the $title variable available sitewide.
Example:
codeObject.$loaded()
.then( function (data) {
$rootScope.$title = data.title;
}
|
It is with using the angular-ui-title approach.
Using $rootScope.$on(…)
In this approach ui-router permits adding arbitrary key: value stuff to our $state config, available to be referenced anywhere we want anytime.
Example:
.state( 'detail' , {
url: '/codes/:codeId' ,
templateUrl: 'codes/detail.html' ,
controller: 'DetailController' ,
data: {
title: 'Code Detail'
}
})
|
With this approach, we need an extra intermediary approach within the .run function of our app.
.run([ '$rootScope' , '$state' ,
function ($rootScope, $state) {
$rootScope.$on( '$stateChangeSuccess' , function () {
$rootScope.title = $state.current.data.title;
});
}
])
|
In index file for this approach replace the $title variable with just title like this
< head >
< title ng-bind = "(title || 'Home') + ' :: CodeBySide'" >
CodeBySide
</ title >
</ head >
About US
Services
Contact US
< head >
< title ng-bind = "(title || 'Home') + ' :: CodeBySide'" >
CodeBySide
</ title >
</ head >
|
Output:
Then doing the snippet from above, with a slight change gets us up and running:
codeObject.$loaded()
.then( function (data) {
$rootScope.title = data.title;
}
|
Last Updated :
23 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...