如何设置角度页面标题 [英] How to set page title with Angular

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

问题描述

我用下面的code,以显示我的每一个AngularJS应用程序模板的页面标题,但每当我试着输入的网址无效测试。否则我得到以下错误:

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的code:

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

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

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