how do return the $state.current.name from ui-router statechange

Matthew Harwood picture Matthew Harwood · Jul 22, 2014 · Viewed 42.3k times · Source

I would like to return the .state('name') when I change location in angular.

From my run() it can return the $state object:

 .run(function($rootScope, Analytics, $location, $stateParams, $state) {
      console.log($state);

working object

but when I try to get$state.current it is empty object

.run(function($rootScope, $location, $stateParams, $state) {

      console.log($state.current);

empty

config example:

 .config(function($stateProvider, $urlRouterProvider, AnalyticsProvider) {  
        $urlRouterProvider.otherwise('/');
        $stateProvider
        .state('home', {
            url: '/',
            views: {
              '': {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
              },
              'navigation@home': {
                templateUrl: 'views/partials/navigation.html',
                controller: 'NavigationCtrl'
              },
              'weekly@home': {
                templateUrl: 'views/partials/weekly.html',
                controller: 'WeeklyCtrl'
              },
              'sidepanel@home': {
                templateUrl: 'views/partials/side-panel.html',
                controller: 'SidePanelCtrl'
              },
              'shoppanel@home': {
                templateUrl: 'views/partials/shop-panel.html',
                controller: 'ShopPanelCtrl'
              },
              'footer@home': {
                templateUrl: 'views/partials/footer.html',
                controller: 'FooterCtrl'
              }
            }
          })

Answer

Sandeep Shabd picture Sandeep Shabd · Jul 22, 2014

You can listen for '$stateChangeSuccess' and set state accrodingly. For example -

$rootScope.$on('$stateChangeSuccess',
  function(event, toState, toParams, fromState, fromParams) {
    $state.current = toState;
  }
)