"optional" params in AngularJS states/views with ui-router

All we need is an easy explanation of the problem, so here it is.

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?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

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

Method 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"
})

Method 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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply