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.

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

That works. Thanks. It would be interesting to know as to why stateParams is not available though.
This post was helpful to understand "run" better for me: stackoverflow.com/questions/20663076/…
Yay! Very helpful. Ty :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.