My implementation of a custom page title follows the ngBoilerplate framework:
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' ;
}
});
})
The issue I encountered is that the browser history saves the updated title for each $stateChangeSuccess
event. For example, when navigating from a page titled "Home" to one titled "About", the history displays "About" as the last item but correctly navigates back to "Home" when clicked. This could potentially confuse users.
To address this problem, I devised a solution by utilizing a workaround in the code:
.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' ;
}
});
})
By temporarily storing the title in a variable and assigning it to the scope only upon $locationChangeSuccess
, I was able to resolve the issue. While this workaround seems effective, I am uncertain of its reliability in the long term.
My main question pertains to achieving a consistently changing page title based on the current state data. How can I modify my approach to ensure a reliable dynamic page title?
Additionally, I am curious about the early firing of the $stateChangeSuccess
event and why it does not work as expected. Is there a specific reason behind this behavior?