gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:28:13 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com