javascript 如何使用 $routeProvider 在 Angular 中更改页面标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26308020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:47:51  来源:igfitidea点击:

How to change page title in Angular using $routeProvider

javascriptangularjsangularjs-routingangularjs-ng-route

提问by Leon Gaban

I found several similar questions, however none of the answers helped. They all seem to involve some type of $locationdependencies that I'm unable to get injected right.

我发现了几个类似的问题,但没有一个答案有帮助。它们似乎都涉及某种$location我无法正确注入的依赖项。

My code below:

我的代码如下:

(function() {

    // App dependencies
    var app = angular.module('portalExchange',
                        ['ngRoute',
                         'app-products',
                         'app-manage',
                         'app-profile']);

    // [ Main Controller ] : PortalController
    app.controller('PortalController', function($scope) {
        if ($('.top_link_dashboard').hasClass('unactive_top')) {
            $('.top_link_dashboard').removeClass('unactive_top');
            $('.top_link_dashboard').addClass('active_top');
        }
    });

    // Controller for Dashboard
    app.controller('DashboardController', function() {
    });

    // Controller for Developers
    app.controller('DevelopersController', function($scope) {
        // Page.setTitle('Developers');
    });

    // Controller for Quote
    app.controller('QuoteController', function($scope) {
        // Page.setTitle('Begin Quote');
    });

    // Directive for Header
    app.directive('appHeader', function () {
        // Type of Directive, E for element, A for Attribute
        // url of a template
        return {
            restrict: 'E',
            templateUrl: 'templates/modules/globals/app-header.html'
        };
    });

    // Directive for Footer
    app.directive('appFooter', function () {
        return {
            restrict: 'E',
            templateUrl: 'templates/modules/globals/app-footer.html',
            controller: function(){
                this.date = Date.now();
            },
            controllerAs:'footer'
        };
    });

    // configure our routes
    app.config(function($routeProvider) {
        $routeProvider

        // route for the dashboard page
        .when('/', {
            templateUrl : 'templates/sections/app-dashboard.html',
            controller  : 'DashboardController'
        })

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

        // route : Developers Page
        .when('/developers', {
            title : 'For Developers',
            templateUrl : 'templates/sections/app-developers.html',
            controller  : 'DevelopersController'
        })

        // route : Begin Quote
        .when('/quote', {
            title : 'Begin Quote',
            templateUrl : 'templates/sections/app-quote.html',
            controller  : 'QuoteController'
        });
    });

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

})();

The RUN function

运行功能

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

HTML

HTML

<!DOCTYPE html>
<html lang="en" ng-app="portalExchange" ng-controller="PortalController as portal">
<head>
    <meta charset="utf-8">
    <title ng-bind="title">myApp</title>
</head>

回答by dfsq

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

我的方法很简单。在路由配置中,您定义title

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

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

然后你监听$routeChangeSuccess事件并设置document.title. 在应用程序运行块中(最好的地方):

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.

这种方法的好处是它可以让您避免更多的绑定ng-bind="title",这很好。

回答by haiiro-shimeji

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).

因为有时 $route 注入会导致问题(例如,在运行单元测试时)。

回答by D. Doyle

This is a little of topic, but I was trying to manage the page title in an angular application that uses ui-routerand I ran into a couple of issues. First, of course, I had to change routeand $routeChangeSuccessto $stateand $stateChangeSuccessand 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:

这是一个小话题,但我试图在使用的角度应用程序中管理页面标题,但ui-router我遇到了几个问题。首先,当然,我不得不改变route$routeChangeSuccess$state$stateChangeSuccess第二,我曾与网页标题的问题之前,浏览器可以添加前一页标题为历史得到更新,所以我不得不添加超时事件处理程序产生以下代码:

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);
    });
}