KenavR
KenavR

Reputation: 3899

UI Router: Access route directly using the url

I thought this would be a really common problem, but I can't find anything about this. I have two states one is accessed on /route and the second one on /route/{name}. It works fine if I call the second route using ui-sref but when I refresh the page or try to access it directly via url I get on the /route page even tough the url in the browser stays the same. How do I fix that?

  function Routes($stateProvider) {

    $stateProvider.state("route1", {
      url: "/route",
      templateUrl: "js/route/route1.html",
      controller: "Route1Controller",
      controllerAs: "vm",
      resolve: {
        ...
      }
    })
    .state("route2", {
      url: "/route/{name}",
      templateUrl: "js/route/route2.html",
      controller: "Route2Controller",
      controllerAs: "vm",
      resolve: {
        ...
      }
    });
  }

Edit: To make it more clear, I would like that route2 acts like any other state with a complete different url. I guess nobody would suggest nested views if the urls where "/route1" and "/route2". If that's not possible I will consider using a nested view in the route1 template.

Edit2: The problem was not with the posted code. I had another route "/route/:id" but I didn't define the type. Therefore the routes where actually the same. I defined the types ("/route/{id:int}") and now it works.

Upvotes: 1

Views: 1282

Answers (3)

Nawideck
Nawideck

Reputation: 61

try this :

$stateProvider.state("route1", {
  url: "/route",
  templateUrl: "js/route/route1.html",
  controller: "Route1Controller",

})
.state("route1.name", {
  url: "/{name}",
  templateUrl: "js/route/route1-name.html",
  controller: "Route1NameController",
});

And in your index.html file :

<body>
    ...
    <div ui-view></div>
    ...
</body>

Upvotes: 1

Gopinath Shiva
Gopinath Shiva

Reputation: 3892

have u tried this, change the state and url to below

$stateProvider
    .state('route1', {            
        url: '/contacts',
    })
    .state('route1.name', {            
        url: '/{name}'
        //...more
    })        

Upvotes: 1

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

The order of state definition decides in this case. The UI-Router will iterate all defined states and try to find the one - which matches to current url. And the first match will decide.

So we just have to declare the scond one as the first:

$stateProvider
// this will be defined as the first 
.state("route2", {
  url: "/route/{name}",
  ...
  }
})
// if no match for /route/param
// this will be used
.state("route1", {
  url: "/route",
  ...
});

Upvotes: 1

Related Questions