Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the "absolute" URL of a state in Angular-UI?

I am using Angular and Angular-UI ui-router. I have some states defined:

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

Note that I am using abstract states. Is there a handy function that gets me the URL of a given state by name? For example I want something like:

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

which should return a value like #/tab/home.

like image 973
tksfz Avatar asked Jun 10 '14 22:06

tksfz


1 Answers

What you are searching for is a built in $state method href(). You can see an example here. The documentation:

  • href(stateOrName, params, options)

How to get the current state href?

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

Let's have this extended mapping (see detailed definition in the 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}}',...
        });

The example of state calls:

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>

And in each of them we can call

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

which will result in the

#/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
like image 59
Radim Köhler Avatar answered Nov 28 '22 15:11

Radim Köhler