angularjs - 如何使用 AngularJS 设置页面标题

标签 angularjs

我使用以下代码来显示每个 AngularJS 应用程序模板的页面标题,但每当我尝试输入无效的 URL 来测试 .otherwise 时,我都会收到以下错误:

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

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

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

索引.html:

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

请提出建议

最佳答案

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

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

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

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

关于angularjs - 如何使用 AngularJS 设置页面标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326307/

相关文章:

css - 使用来自 Nodejs 的 Angularjs 格式化文本文件

javascript - 无法访问 AngularJs Controller 内的代码

javascript - 使用 Angular.js 突出显示 PRISM 的 HTML

angularjs - AJAX 调用后加载指令

javascript - JavaScript Controller 中的 Angular JS 过滤

angularjs - 如何插入带有内插表达式的 HTML 注释?

angularjs - Angular1 应用程序中的 Angular2 组件

javascript - 无法使用 AngularJs 获取文本区域值

javascript - 如何在angularjs指令中使用动态模板

java - 如何将多个对象从 Angular2 发送到 Java Spring 后端