Leon Gaban Leon Gaban - 1 month ago 5
AngularJS Question

How to avoid escaping when trying to replace $location.search?

const createParam = (key, value) => '?'+key+'='+value;

const rebuildUrl = (linkUrl, params) => {
TagsFactory.resetTickerTags();

console.log('params', params);
_.each(params, (param)=> {
linkUrl += createParam(param.key, param.value);
});

console.log('linkUrl', linkUrl);
// window.location.href = linkUrl;
$location.search(linkUrl);
};

const checkForStoredLink = () => {
Util.notEmpty(storedLinkParams) ? rebuildUrl('', storedLinkParams) : null;
};





storedLinkParams = [
{ key: "ticker",
value: "AAPL" },
// etc...


My function above will take in the params array and generate a string like this:
/dashboard?ticker=AAPL?sort=trend?timespan=day?term_id_1=3010695?start_epoch=1473186060?end_epoch=1473358860


My current URL looks like this:

http://localhost/static/dashboard/app/#/dashboard?


And once my function above reaches the
$location.search
line it ended up looking like this, which breaks the UI:

http://localhost/static/dashboard/app/#/dashboard?%3Fticker=AAPL%3Fsort%3Dtrend%3Ftimespan%3Dday%3Fterm_id_1%3D3010695%3Fstart_epoch%3D1473186060%3Fend_epoch%3D1473358860

Answer

$location.search expects search parameters to be delimited by &. e.g.

$location.search('param1=value1&param2=value2'); results in: ?param1=value1&param2=value2

$location.search('?param1=value1?param2=value2') results in: ?%3Fparam1=value1%3Fparam2.

If you start using & to delimit the params then your life can be even simpler, you can pass in an object and avoid any string building:

$location.search(_.fromPairs(params, param => [param.key, param.value]));

Code above assumes the _ is a recent version of lodash.js, if not:

_.each(params, param => $location.search(param.key, param.value));

To answer the question in the title: If you really want to set raw urls yourself, then a solution to that could be to inject your own wrapper around window.location, but would not recommend