如何使用AngularJS设置页面标题 [英] How to set page title with AngularJS

查看:474
本文介绍了如何使用AngularJS设置页面标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来显示每个AngularJS应用模板的页面标题,但是每当我尝试输入无效的URL来测试时,都会出现以下错误:

I am using the following code to display page titles for each of my AngularJS app template, but whenever I try to enter an invalid URL to test the .otherwise I get the following error:

TypeError: Cannot read property 'title' of undefined
    at http://localhost/app/js/app.js:34:43

下面是使用的app.js,index.html代码:

Below is the app.js, index.html code used:

app.js:

var myApp = angular.module('myApp', ['ngRoute', 'ngSanitize']);
myApp.config(['$routeProvider', function($routeProvider) {

       $routeProvider.when('/home', 
                {     templateUrl: 'templates/index.html', 
                      controller: 'MainController',
                      title: 'Welcome to Home Page'
                });
        $routeProvider.otherwise({
                                    redirectTo: '/home'

                                 });

}]);


myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

Index.html:

Index.html:

<title ng-bind="title +' - MyAPP Home'"> - MyApp</title>

请提出建议

推荐答案

无论如何都将触发$routeChangeSuccess事件,因此请通过测试路由的存在来避免错误:

The $routeChangeSuccess event will be triggered no matter what, so avoid the error by testing the existence of the route:

myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {

        if (current.hasOwnProperty('$$route')) {

            $rootScope.title = current.$$route.title;
        }
    });
}]);

这篇关于如何使用AngularJS设置页面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆