Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular ui-router parent url set to /

Using ui-router and setting the parent state url to / results in my url looking like localhost:8000/#//child when looking at a child page. I'd like just a single / between the hash and child.

I tried leaving the parent state url blank, but then ui-sref won't link back to the parent state when using an anchor link. Anybody got a solution for having a root level un-named parent url?

app.config

app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");

$stateProvider
  .state("main", {
    url: "/",
    templateUrl: 'sites/main/main.html',
    controller : 'MainController',
    resolve: {
      items: function(srvMenu) {
          return srvMenu.getNav();
      }
  }

 })

});

child.config

emergency.config(function($stateProvider) { 
$stateProvider
    .state("main.emergency", {
      url: "/emergency",
      templateUrl: 'sites/emergency/emergency_menu.html',
      controller : 'EmenuController',
      resolve: {
          emenu: function(srvEmergency) {
              return srvEmergency.getMenu();
          }
      }

    })

    .state("main.emergency.detail", {
      url: "/detail",
      templateUrl: 'sites/emergency/emergency_detail.html',
    })
});
like image 381
Jeffrey Avatar asked May 20 '14 22:05

Jeffrey


1 Answers

The ui-router has solution (almost) for anything. There is a working plunker. The feature we will se in action is called: Absolute Routes (^)

So, let's start with requirement, to have these URL routes:

domain/#/                             -- root for main
domain/#/emergency/                   -- main.emergency
domain/#/emergency/detail             -- main.emergency.detail

Which should be working when using this ui-sref state calls:

<ul>
    <li><a ui-sref="main">Main</a></li>
    <li><a ui-sref="main.emergency">Emergency</a></li>
    <li><a ui-sref="main.emergency.detail">Detail</a></li>
</ul> 

Now, the trick is:

  • the root (first) state must use url: "/", to have some unique identification
  • but the next state can start its definition from the root again: with this setting:
    url: "^/..."

Here is the state configuration, enabling the desired results

  $stateProvider
    // root with '/'
    .state("main", {
      url: "/",
      templateUrl: 'main.tpl.html',
    })
    // here we start again from the root '/emergency'
    .state("main.emergency", {
      url: "^/emergency",
      templateUrl: 'emergency_menu.tpl.html',
    })
    // parent and child '/emergency/detail
    .state("main.emergency.detail", {
      url: "/detail",
      templateUrl: 'emergency_detail.tpl.html',
    });

And here is the documentation:

Absolute Routes (^)

...and the working plunker...

like image 89
Radim Köhler Avatar answered Nov 14 '22 17:11

Radim Köhler