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

I am using Angular and Angular-UI ui-router . I have several 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"
            }
        }
    });

Please note that I am using abstract states. Is there a convenient 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 similar to #/tab/home.

+4
source share
1 answer

What you are looking for is a built-in method $state href(). Here you can see here . Documentation:

How to get the current state of 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
+8

Source: https://habr.com/ru/post/1544064/


All Articles