Search code examples
angularjsangular-ui-routerangular-factory

broadcast state name Angular js $stateChangeStart


I want to create a factory which should return current state's name, i tried this code inside a controller:

$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
     $rootScope.tabName  = fromState.name;          
 });

but this information is available only if the particular controller is called, i want to make this information available throughout the project.


Solution

  • You can do it other way around.

    angular.module('app')
    .run(['$state', '$cookies', '$rootScope', function($state, $cookies, $rootScope) {
        $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    
            $rootScope.tabName  = fromState.name;       
        });
    });
    

    Rather than putting it in controller, Use it in run method of module which will be called at the time of initialization of application.