0

I wish to attach a listener to URL changes in the ui.router module I use in an AngularJS app, because I need to get the new state and its url when the url changes. In order to customize the url change listener, I've done the following, but it's not working (yet):

in the config section of ui.router, I added this line:

$urlRouterProvider.deferIntercept();

and after the config(), I have the following code, hoping to cactch the ui.router's state and its url

config(
//ui.router's config ommitted....
).run(function($rootScope, $urlRouter) {
    $rootScope.$on('$locationChangeSuccess', function(e) {
          console.log(e);

          e.preventDefault(); //prevent the default handler
          $urlRouter.sync(); //once the interception is done, sync the current url
         $urlRouter.listen();
    })
});

I am not sure if this is possible to do with ui.router. Or there is a much easier way to get the state and its url?

TonyW
  • 18,375
  • 42
  • 110
  • 183

1 Answers1

2

I am not 100% sure what is the real requirement behind. But with UI-Router, we should use $stateChangeStart event I'd say.

There is an example, a working plunker

$rootScope.$on('$stateChangeStart', function (event, toState,   toParams
                                                   , fromState, fromParams) 
{
  console.log(event)
  console.log(toState)
  console.log(toParams)
  console.log(fromState)
  console.log(fromParams)
  console.log(toState)
  console.log($location.url())
});

Check it here

The $urlRouter and its .deferIntercept() and .listen() or more useful for declaring states in a .run() phase

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

      $stateProviderRef = $stateProvider; 

      $urlRouterProvider.otherwise('/home');
      $urlRouterProvider.deferIntercept();

// run
.run(['$rootScope', '$urlRouter',
  function($rootScope, $urlRouter) {    

    $stateProviderRef
      .state('home', {
        url: "/home",
        templateUrl: 'tpl.html',
      })
    $urlRouter.listen();
  }
]);
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335