Reputation: 17553
I am trying to dynamically set page title in AngularJs. I'm using angular-ui router and stateHelper.
So I have this in my main template:
<title ng-bind="pageTitle"></title>
And this in my ui-router:
{
name: 'show',
url: '/:id',
title: function($stateParams){
return 'Showing '+$stateParams.id;
}
}
Then this:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams)
{
//set page title
if(angular.isFunction(toState.title))
{
var callBack = toState.title; //this is the anonymous function
//I expect the anonymous function to return the title
$rootScope.pageTitle = callBack;
}else{
$rootScope.pageTitle = toState.title;
}
}
The Challenge:
var callBack = toState.title;
returns a string like this "function($stateParams){return 'Showing '+$stateParams.id;}"
How do I execute this function and also respect the parameters dependency injected
parameters passed along with it (unknown number of DI)
NB: I am so scared of eval
and wouldn't like to use it :(
Upvotes: 0
Views: 87
Reputation: 222795
A function can be invoked with relevant dependencies with $injector.invoke
:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams)
{
if(angular.isFunction(toState.title) || angular.isArray(toState.title))
{
$rootScope.pageTitle = $injector.invoke(toState.title);
}else{
$rootScope.pageTitle = toState.title;
}
}
As any other DI-enabled function, title
should be annotated accordingly, it may be either a function or an array.
Upvotes: 1
Reputation: 683
You can inject $stateParams into the controller (where the $rootScope.$on statement in) first, and call
toState.title($stateParams);
By the way, you can consider use a better solution to handle "dynamic title". Check the way this project use: https://github.com/ngbp/ngbp
Upvotes: 0