我使用以下代码显示每个AngularJS应用程序模板的页面标题,但每当我尝试输入无效的URL来测试.otherwise时,我会收到以下错误:
TypeError: Cannot read property 'title' of undefined
at http://localhost/app/js/app.js:34:43
Run Code Online (Sandbox Code Playgroud)
以下是使用的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;
});
}]);
Run Code Online (Sandbox Code Playgroud)
index.html的:
<title ng-bind="title +' - MyAPP Home'"> - MyApp</title>
Run Code Online (Sandbox Code Playgroud)
请建议
小智 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;
}
});
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44290 次 |
| 最近记录: |