25

I am using states to change data in a table. URLs are of the form /zone/:zoneCode.
However, when just /zone is accessed I want it to default to a certain zoneCode.

This is my code:

.state('zone',
{
    url:'/zone',
    controller:'ZoneController',
    templateUrl:'views/zone.html'
})
.state('zone.code',
{
    url:'/:zoneCode',
    templateUrl:function(stateParams)
    {
        return 'views/zone-codes/'+stateParams.zoneCode+'.html';
    }
}

The template loaded for each subview contains a table that displays data.
When no zoneCode is present in the URL, the table doesn't exist because the ui-view didn't know to load a templateUrl.

How can I set a default for the parent state?

Thanks.

Francisc
  • 77,430
  • 63
  • 180
  • 276
  • What? It's not even close to duplicate... That question is about setting a fallback for unmapped URLs, my question is about changing a child state from a controller. – Francisc Dec 18 '13 at 09:48

2 Answers2

57

Although the question is quite old, I would still like to provide an answer as I had the same problem. The answer can be found in this Stackoverflow question. To apply that answer to your case:

$urlRouterProvider.when('/zone','/zone/'+zoneCode);

The urlRouterProvider checks to see if the url is [yoururl]/zone. If this is the case, it will redirect to the [yoururl]/zone/zoneCode, with the zoneCode as the one you specified.

Hope it helps someone!

Community
  • 1
  • 1
IvorG
  • 864
  • 7
  • 10
15

You can also this, it'll handle routes that don't exist by redirecting to a default route set by you.

$urlRouterProvider.otherwise('/');

$stateProvider.state("zone", {
    url: "/",
    templateUrl: "views/zone.html",
});
Alexis Tyler
  • 1,394
  • 6
  • 30
  • 48