Ui-router deferIntercept and state parameters

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

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

Using this code, clicking on the browser return button changes the URL to the previous one, but I cannot update my controller state to reflect this change. $ stateParams still contains the values ​​set when the user first loads the page.

What is the best way to update the $ state and $ stateParams objects inside my controller when the user clicks the back button or manually changes the URL?

thanks!

+8
javascript angularjs angular-ui-router
source share
1 answer

Your call to $urlRouter.listen() should be placed outside the event handler. The output code fragment 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 sample code for the deferIntercept method. It places a call to $urlRouter.listen() outside 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 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 listener *after* your custom listener $urlRouter.listen(); }); 
+7
source share

All Articles