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
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' } }) // other states here ..... )]); |
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; // update title with detail page // other code here } |
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; // update title with detail page // many code here } |
Please Login to comment...