2

I have a search from with multiple optional fields, I don't feel I've handled this correctly in the past and want to know how to correctly handle this so that results will reload should a user refresh the page after going through the search form.

I have a form that people can use to search for clients, my users can search by type, name, account number

type is a required field

name and account number are optional fields.

I can use the $routeProvider to configure my routes something like:

.when('/clientSearch/:type/:accountNumber?/:name?', {

but if account number and name are optional how do I distinguish if only one of the two is being passed in? Some forms have multiple optional numeric/string fields.

Using $location.search() I can set the URL params, like:

$location.search( {type: type, accountNumber: accountNumber, 'name': name} )

Which is the preferred method, coming at this wrong?

How do you properly handle search forms and allow the same results to be fetched again if the page is refreshed?

1
  • 2
    They should be query params. Commented Nov 25, 2014 at 20:52

1 Answer 1

1

Typically you use query params. In angular they are called search params:

See https://docs.angularjs.org/api/ng/service/$location

And use like so:

// http://example.com/#/some/path?foo=bar&baz=xoxo

// To get:
$location.search()  // => {foo: 'bar', baz: 'xoxo'}

// To set:
$location.search('foo', 'yipee') // => {foo: 'yipee', baz: 'xoxo'}

To your questions:

Which is the preferred method, coming at this wrong?

The preferred method is definitely to use query/search params

How do you properly handle search forms and allow the same results to be fetched again if the page is refreshed?

Grab the params and define whatever is needed in your controller. If you need params available to the view, you can do things like:

$scope.searchParams = $location.search()
Sign up to request clarification or add additional context in comments.

1 Comment

Take care not to confuse $location.search() and native Location.searchParams (a.k.a. "query string params"), as these are two different things. $location.search() is concerned with part of Location.hash while Location.searchParams are parsed values from Location.search (query string). The important part is, changing the hash doesn't reload the page like changing the query string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.