在Angular UI Router中,可以通过使用$rootScope
和$stateChangeSuccess
事件来设置页面的标题。
首先,需要在应用的主控制器中注入$rootScope
:
app.controller('MainController', function($rootScope) {
// ...
});
然后,在$stateChangeSuccess
事件中,通过使用$rootScope
的title
属性来设置页面的标题:
app.run(function($rootScope) {
$rootScope.$on('$stateChangeSuccess', function(event, toState) {
if (toState.data && toState.data.title) {
$rootScope.title = toState.data.title;
} else {
$rootScope.title = 'Default Title'; // 设置默认标题
}
});
});
在上述代码中,我们检查了目标状态对象(toState
)是否有data
属性,并且是否有title
属性。如果有,我们将其赋值给$rootScope.title
,否则设置默认标题。
最后,在HTML模板中,可以使用{{title}}
来动态显示页面的标题:
这样,每当切换到新的状态时,页面的标题就会被更新为对应状态的标题。
下面是一个完整的示例:
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
data: {
title: 'Home Page' // 设置标题为'Home Page'
}
})
.state('about', {
url: '/about',
templateUrl: 'views/about.html',
data: {
title: 'About Page' // 设置标题为'About Page'
}
});
$urlRouterProvider.otherwise('/home');
});
app.controller('MainController', function($rootScope) {
$rootScope.$on('$stateChangeSuccess', function(event, toState) {
if (toState.data && toState.data.title) {
$rootScope.title = toState.data.title;
} else {
$rootScope.title = 'Default Title'; // 设置默认标题
}
});
});
在上述示例中,当切换到home
状态时,页面的标题会变成Home Page
;当切换到about
状态时,页面的标题会变成About Page
。如果切换到一个没有设置title
的状态,则会显示默认标题Default Title
。