2

I would like to be able to access the url parameters in my run function and make actions based on those params. However, I was pretty surprised to see that ui.router's $stateParams object is empty in my run function.

angular.module('app', ['ui.router'])
.run(['$rootScope', '$state', '$stateParams', '$location', function($rootScope, $state, $stateParams, $location) {
    $rootScope.$state = $state;
    $rootScope.location = $location;
    $rootScope.$stateParams = $stateParams;
    $rootScope.$on('$stateChangeStart', function(event, toState) {
      if (toState.name === 'main') {
      event.preventDefault();
      $state.go('main.child', {

        param: 1

      })
      }
    });
    console.log('$stateParams is empty!');
    console.log($stateParams);
    console.log($rootScope.$stateParams);
}])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {

    $stateProvider
        .state('main', {

            url: '',
            template: '<div>hey</div><div ui-view></div>'

        })
        .state('main.child', {

            url: '/:param',
            template: 'child state template'


        });
}]);

Is it possible to access the params accessed from $stateParams in the run function? Or are they only available in the config function? Why are they not accessible in the run function?

Plnkr: http://plnkr.co/edit/1YXKRmR48LyxbGXWq66Y?p=preview

Thanks for any help.

nikk wong
  • 8,059
  • 6
  • 51
  • 68

1 Answers1

8

It looks like you are using StateChangeStart event and you can access parameters in this event:

 $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
//you code goes here
console.log(toParams);
}

I am using it to add some custom logic to parametrs (authentication redirects)

JanisP
  • 1,233
  • 15
  • 16