我使用以下代码来显示每个 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/