28

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?

3 Answers 3

25

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The first option doesn't work. For search/John/Smith I get fn="" and no ln. Using query params seems to cause the params to "stick" to the URL in further states/views, which is not acceptable.
It may be fixed, but it is not on the latest release (0.2.10) as of 6/23/2014.
v0.2.10. For me fn matches leading / as well. I.e. in /search/123 fn is matched to /123
11

You can use:

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

1 Comment

It is not optional, even if we don't need to pass anything then ...com/search will not work but we need to use ...com/search// which is not good.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.