具有有限选项的Angular JS路由参数

时间:2016-07-28 09:46:52

标签: angularjs url url-parameters ngroute

我刚开始使用Angular并且目前正在使用1.4.2。 我想知道如何只为网址/:type提供三个选项 - 创建,更新和查看。

他们都使用相同的控制器,所以我不想有单独的罢工,如

.when('/create ... , .when('/update ... , .when('/view ... .

我不想在这些旁边传递任何其他选项。 如果我能得到一些帮助,那就太好了! 谢谢:))

2 个答案:

答案 0 :(得分:2)

您可以从控制器上的$ routeParams服务获取参数,并执行您想要使用的任何逻辑。见https://docs.angularjs.org/api/ngRoute/service/ $ routeParams

路线配置

$routeProvider
    .when("/yourroute/:type", {
        template: "default"
        templateUrl: "template.html",
        controller: "Controller"
    });

控制器功能

function Controller($routeParams) {
    switch($routeParams.type) {
        case "create":
            ...
        case "update":
            ...
        case "view":
            ...
        default:
            ...
    }
}

答案 1 :(得分:0)

但你想要3个难度网址吗?您应该使用ui-router和stateHelperProvider来使用子语句,而您不希望在何时声明多个。你应该可以做类似

的事情
stateHelperProvider.state({
            name: 'root',
            template: '<ui-view/>',
            abstract: true,
            children: [
                    {
                        name: 'create',
                        url: '/create',
                        templateUrl: 'mypath.html',
                        controller: 'myCtrl',
                        data: {
                            type: 'create'
                        }
                    },
                {
                    name: 'view',
                    url: '/view',
                    templateUrl: 'mypath.html',
                    controller: 'myCtrl',
                    data: {
                        type: 'view'
                    }
                },
                {
                    name: 'update',
                    url: '/update',
                    templateUrl: 'mypath.html',
                    controller: 'myCtrl',
                    data: {
                        type: 'update'
                }
                },
            ]
            });

每次使用您的数据时都会显示。 但我不明白,你没有宣布3“何时”