I am migrating my AngularJS based app to use ui-router instead of the built in routing. I have it configured as shown below
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl : 'views/home.html',
data : { pageTitle: 'Home' }
})
.state('about', {
url: '/about',
templateUrl : 'views/about.html',
data : { pageTitle: 'About' }
})
});
How can I use the pageTitle variable to dynamically set the title of the page? Using the built in routing, I could do
$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
$rootScope.pageTitle = $route.current.data.pageTitle;
});
and then bind the variable in HTML as shown below
<title ng-bind="$root.pageTitle"></title>
Is there a similar event that I can hook into using ui-router? I noticed that there are 'onEnter' and 'onExit' functions but they seem to be tied to each state and will require me to repeat code to set the $rootScope variable for each state.
Use
$stateChangeSuccess
.You can put it in a directive:
And:
Demo: http://run.plnkr.co/8tqvzlCw62Tl7t4j/#/home
Code: http://plnkr.co/edit/XO6RyBPURQFPodoFdYgX?p=preview
Even with
$stateChangeSuccess
the$timeout
has been needed for the history to be correct, at least when I've tested myself.Edit: Nov 24, 2014 - Declarative approach:
And:
Demo: http://run.plnkr.co/d4s3qBikieq8egX7/#/credits
Code: http://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview
The angular-ui-router-title plugin makes it easy to update the page title to a static or dynamic value based on the current state. It correctly works with browser history, too.
Why not just:
UPDATE: Full Directive Code
Then in every page you would just include this directive:
There is a another way of doing this by combining most of the answers here already. I know this is already answered but I wanted to show the way I dynamically change page titles with ui-router.
If you take a look at ui-router sample app, they use the angular .run block to add the $state variable to $rootScope.
With this defined you can then easily dynamically update your page title with what you have posted but modified to use the defined state:
Setup the state the same way:
But edit the html a bit...
I can't say this is any better than the answers before... but was easier for me to understand and implement. Hope this helps someone!
I found this way really easy:
and then in my HTML like this:
You are actually really close with your first answer/question. Add your title as a data object:
In your index.html bind the data directly to the page title: