将指令更新为:
myApp.directive('testTitle', function($rootScope, $timeout) {
return {
restrict: 'E',
template: `<title>{{$root.title}}</title>`,
link: function() {
var listener = function(event, toState) {
$timeout(function() {
$rootScope.title = (toState.data && toState.data.pageTitle) ? toState.data.pageTitle : 'Default title';
});
};
$rootScope.$on('$stateChangeSuccess', listener);
}
};
});
在这里,当您在模板中使用$rootScope作为标题变量时,您必须使用
{{$root.title}}
. 之后,只需添加
test-title
Working Plunker
还要确保您使用的是0.4.2版本的ui路由器。对于ui路由器的最新版本(1.x),不推荐使用$statechangesccess事件。使用
$transitions.onSuccess
相反
Official Documentation
issue