猿问

如何在 url 中记录页面搜索条件

问题描述

在一个页面,有很多搜索选项,比如十几个。假设全部都有选中,那么查询参数就会有十几个。我想把这些参数都放到 url 上,这样即使页面刷新也能还原之前的搜索条件

我用的是 angular(1.2.5) + ui-router(0.2.18) 来做的,目前的代码是这样的

贴代码

结果是

无法进入 main.enter.paper ,原因就是设置了很多 stateParams ,但是没有给默认值, 因为那些都是可选参数。

我的期望是

最好设置路由的时候只需要这样设置

https://img1.mukewang.com/5c32b81e0001a27f06870550.jpg

还有之所以不用 location.href 是因为这个会刷新页面,不知各位有什么好办法?

一只萌萌小番薯
浏览 727回答 1
1回答

冉冉说

ok, 我找到一个可以实现的方法,贴代码如下:$stateProvider&nbsp; &nbsp; &nbsp; &nbsp; .state('main', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: '/',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; templateUrl: 'main.html',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controller: 'MainCtrl',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controllerAs: 'mn'&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .state('main.enter', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: '^/enter',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; template: '<div ui-view class="enter"></div>'&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .state('main.enter.paper', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: '^/enter/paper/:page?sort=1&per_page&publisher_id&school_stage_id&subject_id&volume_id&grade_id&type_id&level&year&province_id&area_id&city_id&time_start&time_end',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; templateUrl: 'enter_paper.html',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controller: 'EnterPaperCtrl',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controllerAs: 'ep'&nbsp; &nbsp; &nbsp; &nbsp; });就是在定义 url 的时候,后面先定义可选参数,'^/enter/paper/:page?sort=1&per_page&publisher_id,这样,在进入 'main.enter.paper' 后,地址栏可以看到 url 是 /enter/paper/1?sort=1&per_page=10,因为我进入 EnterPaperCtrl 就更新了一次 url,更新参数就是 {page: 1, sort: 1, per_page: 10},然后如果选中出版社,查询后更新 url,var params = {&nbsp; &nbsp; page: 1,&nbsp; &nbsp; sort: 1,&nbsp; &nbsp; per_page: 10,&nbsp; &nbsp; publish_id: '38dfjdfkj889'};$state.go('.', params, {notify: false});可以看到 url 将更新为 /enter/paper/1?sort=1&per_page=10&publish_id=38dfjdfkj889
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答