本文介绍了需要在 url 更改时捕获 ui.router 状态及其 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我在 AngularJS 应用程序中使用的 ui.router 模块中为 URL 更改附加一个侦听器,因为我需要获取 new state 及其 url 当 url 改变时.为了自定义 url 更改侦听器,我执行了以下操作,但(还)不起作用:

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):

在 ui.router 的配置部分,我添加了这一行:

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

$urlRouterProvider.deferIntercept();

在config()之后,我有下面的代码,希望能捕捉到ui.router的状态和它的url

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

我不确定这是否可以与 ui.router 一起使用.或者有更简单的方法来获取 state 及其 url?

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?

推荐答案

我不是 100% 确定背后的真正需求是什么.但是对于 UI-Router,我们应该使用 $stateChangeStart 事件.

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

一个例子,一个工作的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())
});

此处查看

$urlRouter 及其 .deferIntercept().listen() 或更有用的用于在 中声明状态.run() 阶段

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

这篇关于需要在 url 更改时捕获 ui.router 状态及其 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:40