2014-06-10 26 views
4

我正在使用Angular和Angular-UI ui-router。我定義了一些狀態:在Angular-UI中獲取狀態的「絕對」網址?

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

+0

你爲什麼需要它?如果你的路線中有變量(例如'/ home /:someVar'),你會發生什麼? –

+0

我只想在某些地方通過州名來引用URL,而不是在任何地方對網址進行硬編碼。 – tksfz

回答

7

你在搜索的是一個內置的$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 
+0

真棒完美答案。忽略了文檔中的一個。 – tksfz

+0

偉大的,如果有幫助;)享受令人敬畏的'ui路由器' –