Gethin Oakes Gethin Oakes - 4 months ago 10
AngularJS Question

AngularJS change single URL parameter on load if it matches a value

I'm working on a web app where parameters get passed to views as you navigate through the site. These parameters are set by user filters.

I've hit a problem whereby some views don't support a specific value from one of the filters, and where this happens the parameter needs to be reset to one out of two possibilities.

I've been using

$location.search({ type: "blue" })
but I've realised that if there are other parameters in the url/on the view, these get removed in place for just the one that is set using that code.

Basically, on some views if the
type
parameter is
all
it needs to change to
blue
, and on others it would need to change to
red
.

Unfortunately this parameter is set in the link by the current filter that is applied, so its not as simple as just changing the href.

You can see here in this example I'm trying to change views that can only be set as
red
to
red
when coming from a view where
blue
was set (and in the link) using an array of paths.

for (let i = 0; i < redOnlyViews.length; i++) {
if (newUrl.indexOf(redOnlyViews[i]) > -1 && type === "blue") {
$location.path("/" + redOnlyViews[i]).search({type: "red"});
}
}


(this is inside a
$rootScope.$on("$locationChangeStart", function (event, newUrl, oldUrl)
function)

If there is a way of changing a parameter like this whilst not changing any of the other parameters that would be fantastic!

Hope this makes sense and thanks :)

changed things to colours for anonymity, I'm not mad :)

rob rob
Answer

If you want to set a single search parameter you can do

$location.search(angular.extend($location.search(), {type: 'red'}))
Comments