2

I implemented a custom page title according to ngBoilerplate:

https://github.com/ngbp/ngbp/blob/v0.3.1-release/src/app/app.js

.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if ( angular.isDefined( toState.data.pageTitle ) ) {
      $scope.pageTitle = toState.data.pageTitle + ' | ngBoilerplate' ;
    }
  });
})

So basically, the title changes on each $stateChangeSuccess event. The problem is, that in my browser history, it saves the new title as the title of the last page. So for instance if I am at a page with the title "Home" and navigate to a page with the title "About", my history will show "About" as last item, but navigate correctly to "Home" when I click on it. I fear that this will really confuse people.

So I came up with a "hack", that seems to solve this problem:

.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
  var nextTitle = "";

  $scope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {
    $scope.pageTitle = nextTitle;
  });

  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if ( angular.isDefined( toState.data.pageTitle ) ) {
      nextTitle = toState.data.pageTitle + ' | ngBoilerplate' ;
    }
  });
})

So now, the title will be save in a variable first and will be assigned to the scope only on $locationChangeSuccess. This seems to work, but I don't know how reliable this is.

So my question is, I guess, how to do this correctly. How do I get a reliable changing page title, that gets it's data from the current state?

And furthermore out of interest: Why doesn't it work with $stateChangeSuccess? Is there a reason why this event fires so early?

basilikum
  • 10,378
  • 5
  • 45
  • 58

3 Answers3

0

See this answer to the more generic question of setting the page title in UI-router. The workaround is to use the $timeout service to run the title update asynchronously. The function will be run after the current script finishes.

$rootScope.$on("$stateChangeSuccess", function (event, toState) {
  $timeout(function () {
    // Needed to ensure the title is changed *after* the url change
    // Ensures history entries are correct.
    $window.document.title = toState.name; 
  });

});

Community
  • 1
  • 1
Chic
  • 9,836
  • 4
  • 33
  • 62
0

Mean.js provides a great page-title directive for that.

Shanavas M
  • 1,581
  • 1
  • 17
  • 24
-3

Have a look at how it's done here: UI Router Sample - index.html

<!-- could easily use a custom property of the state here instead of 'name' -->
<title ng-bind="$state.current.name + ' - ui-router'">ui-router</title>
Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
Pensierinmusica
  • 6,404
  • 9
  • 40
  • 58
  • A code snippet or explanation would be useful in case the linked project gets modified or removed. – Patrick Sep 24 '14 at 19:58