问题
How I spend a parameter title of the post, to display the browser's title?
I use pageTitle parameter on my route, but if put directly: slug as a value, not works.
.state('posts',{
url : '/blog/:slug',
templateUrl : 'content/templates/single.html',
controller : 'SinglePostController',
data: {
pageTitle: 'title'
},
access: {
requiredLogin: false
}
})
回答1:
The data : {}
setting is static.
see similar:
- Accessing parameters in custom data
If you want some dynamic feature use resolve : {}
Some links to examples and Q & A about resolve
- Angularjs ui-router abstract state with resolve
EXTEND: A simple (really naive but working) example how to use resolve
and $rootScope
to manage browser title (check it here):
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
resolve: {
'title': ['$rootScope', function($rootScope){
$rootScope.title = "Other title";
}],
}
})
.state('parent', {
url: "/parent",
templateUrl: 'tpl.html',
resolve: {
'title': ['$rootScope', function($rootScope){
$rootScope.title = "Title from Parent";
}],
}
})
.state('parent.child', {
url: "/child",
templateUrl: 'tpl.html',
controller: 'ChildCtrl',
resolve: {
'titleFromChild': ['$rootScope', function($rootScope){
$rootScope.title = "Title from Child";
}],
}
})
And this could be the html
<!DOCTYPE html>
<html ng-app="MyApp" ng-strict-di>
<head>
<title>{{title}}</title>
Try it here
A challenge here is - what to do on navigation from child to parent, but it could be done by moving that setting into controller and work with $scope.$on('detsroy'
...
Here is adjusted plunker
.state('parent.child', {
url: "/child",
templateUrl: 'tpl.html',
controller: 'ChildCtrl',
// no resolve, just controller fills the target
})
.controller('ChildCtrl', ['$rootScope', '$scope', function ($rootScope, $scope) {
var title = $rootScope.title;
$rootScope.title = "Title from Child";
$scope.$on('$destroy', function(){$rootScope.title = title});
}])
来源:https://stackoverflow.com/questions/33466662/angular-ui-router-title-dynamic