“optional” params in AngularJS states/views with ui-router

烂漫一生 提交于 2019-12-20 16:25:17

问题


I have a customer search view that, by default, simply loads a form for first and last name. It can, however, take those params as arguments in the URL. My app config contains:

    $stateProvider
        .state({
            name:        "search",
            url:         "/search",
            templateUrl: "partials/customerSearch.html",
            controller:  "CustomerSearchCtrl"
        })
        .state({
            name:        "searchGiven",
            url:         "/search/:fn/:ln",
            templateUrl: "partials/customerSearch.html",
            controller:  "CustomerSearchCtrl"
        })

This works, but it seems like it has unnecessary redundancies. Is there a better way? Is this something $urlRouterProvider should handle?


回答1:


There's an issue in ui-router tracker about optional parameters. As of now, you can not specify them in clear way, but you can use regular expressions:

url: '/search{fn:(?:/[^/]+)?}'

or query parameters:

url: '/search?fn&ln'

People are working on it, though, so I'd expect desired functionality to land sometime in the future.




回答2:


You can use:

$stateProvider
.state({
    name:        "searchGiven",
    url:         "/search/{fn}/{ln}",
    params: {
        fn: {value: 'foo'},
        ln: {value: 'bar'}
    },
    templateUrl: "partials/customerSearch.html",
    controller:  "CustomerSearchCtrl"
})



回答3:


There is an update, you can do that:

$stateProvider.state("foo", {
  url: "/search/{fn}/{ln}"
});

As nateabele commented at the issue about optional parameters: view here



来源:https://stackoverflow.com/questions/21977598/optional-params-in-angularjs-states-views-with-ui-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!