How to change page title in Angular using $routeProvider

后端 未结 3 517
后悔当初
后悔当初 2020-12-13 21:20

I found several similar questions, however none of the answers helped. They all seem to involve some type of $location dependencies that I\'m unable to get inje

相关标签:
3条回答
  • 2020-12-13 22:06

    This is a little of topic, but I was trying to manage the page title in an angular application that uses ui-router and I ran into a couple of issues. First, of course, I had to change route and $routeChangeSuccess to $state and $stateChangeSuccess and second, I had an issue with the page title getting updated before the browser could add the previous page title to the history, so I had to add a timeout to the event handler resulting the following code:

    angular.module('myApp').run(appRunFunction);
    
    appRunFunction.$inject = ['$rootScope', '$state', '$timeout'];
    
    function appRunFunction($rootScope, $state, $timeout) {
        $rootScope.$on('$stateChangeSuccess', function() {
            $timeout(function() { document.title = $state.current.title; }, 100);
        });
    }
    
    0 讨论(0)
  • 2020-12-13 22:19

    The way I do it is quite simple. In route configuration you define title:

    .when('/dashboard', {
        title : 'My Dashboard',
        templateUrl : 'templates/sections/app-dashboard.html',
        controller  : 'DashboardController'
    })
    

    then you listen $routeChangeSuccess event and just set document.title. In application run block (the best place for this):

    app.run(['$rootScope', '$route', function($rootScope, $route) {
        $rootScope.$on('$routeChangeSuccess', function() {
            document.title = $route.current.title;
        });
    }]);
    

    The benefit of this approach is that it allows you to avoid one more binding ng-bind="title", which is good.

    0 讨论(0)
  • 2020-12-13 22:20

    This is another way

    app.run(['$rootScope', function($rootScope) {
        $rootScope.$on('$routeChangeSuccess', function(_, current) {
            document.title = current.$$route.title;
        });
    }]);
    

    Because sometimes $route injection causes problem (for example, in running unit tests).

    0 讨论(0)
提交回复
热议问题