with $location.search(): how to remove a parameter from the url when it's null

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

$location.search() to set an url

the search parameter which is passed to the search() is set by a form. selecting and deselecting an element causes some parameters value to be “null” and so the url looks like this :

myapp.com/search?type=text&parameter=null

so i would like to remove those “null” parameters from the url. In the documentation, there is a “paramValue” which can be passed as a second parameters to .search(search, paramValue) : If the value is null, the parameter will be deleted.

but i can’t make this work… any suggestion ?

edit: here is a solution based on @BKM explanation

to remove every parameters which are null, it’s necessary to loop through all of them and test each one, like this :

for (var i in search) {
    if (!search[i]) $location.search(i, null);
}
$location.search(search);

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

Using the $location service, you can remove the search param by assigning it a null value:

In the case when your parameter is null, in your case 'parameter' you can remove it from the url by assigning it a null value like;

$location.search('parameter', null);

Hope it helps.

Method 2

You can use $location.search({}) to clear all at once.

Method 3

You can also do:

var search = $location.search();
if (search.parameter == 'null') {
  $location.search({'parameter': null});
}

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