Angularjs UI-Router:正确地将url路径解释为$ urlRouterProvider中的参数

时间:2014-10-15 18:06:15

标签: angularjs angular-ui-router

我在$stateProvider中进行了以下设置:

$stateProvider
    .state('main.newworkspace', {
        url: "/workspace/new",
        templateUrl: "views/main/newworkspace.html",
        controller: "NewWorkspaceCtrl"
    })
    .state('main.workspace', {
        url: "/workspace/:id",
        templateUrl: "views/main/workspace/main.html",
        controller: "WorkspaceCtrl",
        abstract: true
    })
    .state('main.workspace.dashboard', {
        url: "/dashboard",
        templateUrl: "views/main/workspace/dashboard.html",
        controller: "DashboardCtrl"
    })
    .state('main.workspace.info', {
        url: "/info",
        templateUrl: "views/main/workspace/info.html",
        controller: "InfoCtrl"
    })

现在为此应用启用了以下路线:

/workspace/new
/workspace/:id
/workspace/:id/dashboard
/workspace/:id/info

由于/workspace/:id是抽象的,我希望它能自动重定向到/workspace/:id/dashboard。我尝试通过向when()添加$UrlRouterProvider来实现此目的:

$urlRouterProvider.when('/workspace/:id', '/workspace/:id/dashboard');

所以现在它正确地重定向

/workspace/:id ------> /workspace/:id/dashboard

但也重定向/workspace/new

/workspace/new ------> /workspace/new/dashboard

有快速解决方法吗?我也尝试确定$stateParam.id == 'new'函数调用中是否$urlRouterProvider.when(...),但$ stateParam和$ state.params始终为空。

1 个答案:

答案 0 :(得分:3)

我们应该能够以类似的方式给予特殊路线优先权:

// when for the NEW state... will be matching first - and used
$urlRouterProvider.when('/workspace/new'
                       , function($state){$state.go('main.newworkspace');})
// other 'when' as needed...
$urlRouterProvider.when('/workspace/:id', '/workspace/:id/dashboard');

第一个受到重视的.when()将赢得...