Digitlimit Digitlimit - 6 months ago 27
AngularJS Question

How to call an anonymous function stored as a string

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 :(

Answer

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.