我使用以下代码显示每个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;
});
}]);
的index.html:
<title ng-bind="title +' - MyAPP Home'"> - MyApp</title>
请建议
答案 0 :(得分:32)
无论如何都会触发$routeChangeSuccess
事件,因此通过测试路径的存在来避免错误:
myApp.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
if (current.hasOwnProperty('$$route')) {
$rootScope.title = current.$$route.title;
}
});
}]);