ui-router deferIntercept and state params

…衆ロ難τιáo~ 提交于 2019-12-10 02:25:02

问题


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 !


回答1:


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();
});


来源:https://stackoverflow.com/questions/25530322/ui-router-deferintercept-and-state-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!