如何在尝试替换$ location.search时避免转义?

时间:2016-10-14 20:19:49

标签: javascript angularjs url params

 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...

我上面的函数将接受params数组并生成如下字符串: /dashboard?ticker=AAPL?sort=trend?timespan=day?term_id_1=3010695?start_epoch=1473186060?end_epoch=1473358860

我当前的网址如下所示:

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

一旦我上面的函数到达$location.search行,它就会看起来像这样,这打破了用户界面:

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

1 个答案:

答案 0 :(得分:1)

$location.search期望搜索参数由&分隔。例如

$location.search('param1=value1&param2=value2');会产生:?param1=value1&param2=value2

$location.search('?param1=value1?param2=value2')会产生:?%3Fparam1=value1%3Fparam2

如果您开始使用&来划分参数,那么您的生活可以更简单,您可以传入一个对象并避免任何字符串构建:

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

JsFiddle Example

上面的代码假定_是lodash.js的最新版本,如果不是:

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

JsFiddle Example

要回答标题中的问题:如果你真的想自己设置原始网址,那么解决方法就是在window.location周围注入你自己的包装,但不会建议