我根据ngBoilerplate实现了一个自定义页面标题:
https://github.com/ngbp/ngbp/blob/v0.3.1-release/src/app/app.js
.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if ( angular.isDefined( toState.data.pageTitle ) ) {
$scope.pageTitle = toState.data.pageTitle + ' | ngBoilerplate' ;
}
});
})所以基本上,每个$stateChangeSuccess事件的标题都会改变。问题是,在我的浏览器历史记录中,它将新标题保存为最后一个页面的标题。例如,如果我在一个标题为"Home“的页面上导航到一个标题为"About”的页面,我的历史记录将显示"About“作为最后一项,但当我单击它时,会正确导航到"Home”。我担心这真的会让人们感到困惑。
所以我想出了一个"hack",似乎解决了这个问题:
.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
var nextTitle = "";
$scope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {
$scope.pageTitle = nextTitle;
});
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if ( angular.isDefined( toState.data.pageTitle ) ) {
nextTitle = toState.data.pageTitle + ' | ngBoilerplate' ;
}
});
})因此,标题将首先保存在一个变量中,并仅在$locationChangeSuccess上分配给作用域。这似乎是可行的,但我不知道这有多可靠。
所以我的问题是,我想,如何正确地做到这一点。我如何获得一个可靠的改变页面标题,从当前状态获取它的数据?
此外,出于兴趣:为什么它不能与$stateChangeSuccess一起工作?这个事件这么早触发有什么原因吗?
发布于 2016-04-21 03:25:24
有关在UI-router中设置页面标题的更一般问题,请参阅this answer。解决方法是使用$timeout服务异步运行标题更新。该函数将在当前脚本完成后运行。
$rootScope.$on("$stateChangeSuccess", function (event, toState) {
$timeout(function () {
// Needed to ensure the title is changed *after* the url change
// Ensures history entries are correct.
$window.document.title = toState.name;
});});
发布于 2016-11-01 16:34:55
为此,Mean.js提供了一个很棒的page-title指令。
发布于 2014-06-04 01:24:39
看看这里是如何完成的:UI Router Sample - index.html
<!-- could easily use a custom property of the state here instead of 'name' -->
<title ng-bind="$state.current.name + ' - ui-router'">ui-router</title>https://stackoverflow.com/questions/22300320
复制相似问题