Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ui-router deferIntercept and state params

I use the new deferIntercept() of ui-router to update the browser url without reloading my controller:

$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
  e.preventDefault();
  if ($state.current.name !== 'search') {
    $urlRouter.sync();
  }
  $urlRouter.listen();
});

With this code, a click on the browser's back button changes the URL to the previous one, but I'm not able to update my controller state to mirror this change. $stateParams still contains the values set when the user first loaded the page.

What's the best way to update the $state and $stateParams objects inside my controller when the user click the back button or change the URL manually ?

thanks !

like image 813
Simon Watiau Avatar asked Aug 27 '14 14:08

Simon Watiau


1 Answers

Your call to $urlRouter.listen() should be placed outside the event handler. The code snippet you provided should be changed to:

$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
  e.preventDefault();
  if ($state.current.name !== 'search') {
    $urlRouter.sync();
  }
});

// Moved out of listener function
$urlRouter.listen();

Source: The official documentation for $urlRouter provides a code sample for the deferIntercept method. It places the call to $urlRouter.listen() outside of the listener function:

var app = angular.module('app', ['ui.router.router']);

app.config(function ($urlRouterProvider) {

  // Prevent $urlRouter from automatically intercepting URL changes;
  // this allows you to configure custom behavior in between
  // location changes and route synchronization:
  $urlRouterProvider.deferIntercept();

}).run(function ($rootScope, $urlRouter, UserService) {

  $rootScope.$on('$locationChangeSuccess', function(e) {
    // UserService is an example service for managing user state
    if (UserService.isLoggedIn()) return;

    // Prevent $urlRouter's default handler from firing
    e.preventDefault();

    UserService.handleLogin().then(function() {
      // Once the user has logged in, sync the current URL
      // to the router:
      $urlRouter.sync();
    });
  });

  // Configures $urlRouter's listener *after* your custom listener
  $urlRouter.listen();
});
like image 158
Tyler Eich Avatar answered Oct 15 '22 06:10

Tyler Eich