ui-用于手动解析 URL 而不使用视图的路由器

ui-router for manual parsing URL without using views

我想看一个位置,运行一个位置变化时的功能。 我还希望能够通过 运行ning 函数轻松更改位置。 我希望能够使用浏览器后退按钮。

对于 ngRouteui-router

来说,这听起来像是一个不错的任务

没有

我不需要视图、模板和控制器。

我想要 ui-routerngRoute 的强大功能来解析 URL 并获得 stateParams.

换句话说:如何在不使用视图、模板或控制器的情况下在angular中使用路由?

我不确定你的设置是什么,但是如果你控制所有的路线并且它们相当有限,那么你可以尝试添加 "abstract" 状态,它们不需要视图或一个控制器。我认为顺便说一下,这对普通州来说也不是必需的,但不是 100% 确定。

也许如果您为应用程序的顶部定义抽象路由,那么您将获得所有 "theoretical" 个子项的事件。

你可以找到一个抽象状态的例子here

$stateProvider
    .state('contacts', {
        abstract: true,
        url: '/contacts',
    })

现在,如果您转到 /contacts,您应该会得到 stateChange 事件,我想如果您也转到 /contacts/something,您也会得到它。在最坏的情况下,您可能会将整个应用程序定义为这种 parent/child 状态的树,这些状态都是抽象的。

要处理您需要执行的事件:

$rootScope.$on('$stateChangeStart', function(event, toState){ 
    var greeting = toState.data.customData1 + " " + toState.data.customData2;
    console.log(greeting);

听起来您需要的只是 $location 服务。您可以在没有 ngRouteui-route.

的情况下使用它

The $location Service. What does it do?

The $location service parses the URL in the browser address bar (based on window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into the $location service and changes to $location are reflected into the browser address bar.

The $location service:

  • Exposes the current URL in the browser address bar, so you can
    • Watch and observe the URL.
    • Change the URL.
  • Maintains synchronization between itself and the browser's URL when the user
    • Changes the address in the browser's address bar.
    • Clicks the back or forward button in the browser (or clicks a History link).
    • Clicks on a link in the page.
  • Represents the URL object as a set of methods (protocol, host, port, path, search, hash).

-- AngularJS Developer Guide -- Using $location

Events

$locationChangeStart

Broadcasted before a URL will change.

$locationChangeSuccess

Broadcasted after a URL was changed.

-- AngularJS $location Service API Reference

您可以在没有 Angular 路由器或 Angular-UI 路由器的情况下使用 $location 服务。事实上,如果你想滚动你自己的路由器,你可以使用它。