【问题标题】:Get the "absolute" URL of a state in Angular-UI?在 Angular-UI 中获取状态的“绝对”URL?
【发布时间】:2014-06-11 14:10:30
【问题描述】:

我正在使用 Angular 和 Angular-UI ui-router。我定义了一些状态:

app.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider
    .state('tabs', {
        url: "/tab",
        abstract: true,
        templateUrl: "views/tabs.html"
    })
    .state('tabs.home', {
        url: "/home",
        views: {
            'home-tab': {
                templateUrl: "views/home.html"
            }
        }
    });

请注意,我使用的是抽象状态。是否有一个方便的函数可以按名称获取给定状态的 URL?例如我想要这样的东西:

$state.get('tabs.home').absoluteUrl

它应该返回一个类似#/tab/home的值。

【问题讨论】:

  • 为什么需要它?如果您的路线中有变量(例如:/home/:someVar),您希望发生什么?
  • 我只想在某些地方按州名引用 URL,而不是在任何地方对 URL 进行硬编码。

标签: angularjs angular-ui angular-ui-router


【解决方案1】:

您正在搜索的是一个内置的$state 方法href()。你可以看到example here。文档:

如何获取当前状态href?

$state.href($state.current.name);

让我们拥有这个扩展映射(详细定义见plunker

$stateProvider.
        state('tabs', {
            url: '/tab',
            abstract: true,...
        })
        .state('tabs.home', {
            url: '/home',...
        })
        .state('tabs.home.detail', {
            url: '/{id:[0-9]{1,4}}',...
        })
        .state('tabs.home.detail.edit', {
            url: '^/edit/{id:[0-9]{1,4}}',...
        });

状态调用示例:

ui-sref
<ul>
  <li><a ui-sref="tabs.home">Tabs/Home</a></li>
  <li><a ui-sref="tabs.home.detail({id:4})">Tabs/Home id 4</a></li>
  <li><a ui-sref="tabs.home.detail({id:5})">Tabs/Home id 5</a></li>
  <li><a ui-sref="tabs.home.detail.edit({id:4})">Tabs/Home id 4 - edit</a></li>
  <li><a ui-sref="tabs.home.detail.edit({id:5})">Tabs/Home id 5 - edit</a></li>
</ul>
href 
<ul>
  <li><a href="#/tab/home">Tabs/Home</a></li>
  <li><a href="#/tab/home/4">Tabs/Home id 4</a></li>
  <li><a href="#/tab/home/5">Tabs/Home id 5</a></li>
  <li><a href="#/edit/4">Tabs/Home id 4 - edit</a></li>
  <li><a href="#/edit/5">Tabs/Home id 5 - edit</a></li>
</ul>

我们可以在其中的每一个中调用

var href = $state.href($state.current.name);

这将导致

#/tab/home
#/tab/home/4
#/tab/home/5
#/edit/5 -- this state resets the url form the root 
#/edit/5 -- see the (^) at the start of the url definition

【讨论】:

  • 如果有帮助就太好了 ;) 享受很棒的 ui-router
猜你喜欢
  • 2014-08-21
  • 2013-05-14
  • 1970-01-01
  • 2015-07-05
  • 2015-11-19
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多