Tushar Tushar - 6 months ago 14
Javascript Question

How to annotate dependencies in an inline controller while configuring app routes?

I'm getting following error if I don't annotate the dependencies for an inline controller function for a route (I'm using strict DI mode and all other codes are annotated so that js-minification doesn't break my code):

https://docs.angularjs.org/error/$injector/strictdi?p0=function(AuthService,%20$state

Here is the logout route code:

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider', '$urlRouterProvider) {

$stateProvider.state('logout', {
url: '/logout',
controller: function(AuthService, $state) {
AuthService.logout();
$state.go('login');
}
}

}]);


Is there any technique to declare inline annotation for the above two dependent services (AuthService, $state) of the inline controller ?

I know the bellow work-around :

.state('logout', {
url: '/logout',
controller: LogoutController
});


function LogoutController (AuthService, $state) {
AuthService.logout();
$state.go('login');
}
LogoutController.$inject = ['AuthService', '$state'];


this works but just wanted to checkout if anyone knows any smart short-cut ?

rrd rrd
Answer

Try

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider.state('logout', {
     url: '/logout',
     controller: ['AuthService', '$state', function(AuthService, $state) {        
       AuthService.logout();
       $state.go('login');
     }]
  }
}]);

Not sure if that will work. Usually we separate our controllers into files for ease of use, rather than writing them inline in the config.route.js file.