如何使用Angular ui-router设置默认状态

时间:2021-11-05 04:01:24

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.

我使用状态来更改表中的数据。 URL的格式为/ zone /:zoneCode。但是,当只访问/ zone时,我希望它默认为某个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.

为每个子视图加载的模板包含一个显示数据的表。如果URL中不存在zoneCode,则该表不存在,因为ui-view不知道加载templateUrl。

How can I set a default for the parent state?

如何为父状态设置默认值?

Thanks.

谢谢。

2 个解决方案

#1


54  

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 * 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.

urlRouterProvider检查url是否为[yoururl] / zone。如果是这种情况,它将重定向到[yoururl] / zone / zoneCode,zoneCode就是您指定的那个。

Hope it helps someone!

希望它可以帮到某人!

#2


12  

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

#1


54  

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 * 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.

urlRouterProvider检查url是否为[yoururl] / zone。如果是这种情况,它将重定向到[yoururl] / zone / zoneCode,zoneCode就是您指定的那个。

Hope it helps someone!

希望它可以帮到某人!

#2


12  

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