Can I set a parameter using ngRoute?

跟風遠走 提交于 2019-12-11 14:03:33

问题


I am making an app that shows a list of items, and that list can then be refined by multiple filters. If I were to fetch a list of those options from the URL string, then that would allow visitors to share (or bookmark) a link that takes you to a filtered list of data. But my questions is how would I write those options to the URL string?

So the idea is that once a select element has been changed, to refine the results. Let's say for example that it's just the order of the items.

<select ng-model="order" ng-change="changeOrder()">
  <option ng-repeat="['date', 'amplitude', 'name'] as option">{{ option }}</option>
</select>

I would want to write that option into the URL string, so that it now contains (if you've selected amplitude) ?order=amplitude. Now, if you refresh the page, the data can easily be sorted by amplitude again.

But when there is a lot of those filters and sorting options, and they can be both set or reset to default, it becomes rather difficult to put those options all together, to check if an option is already in the string so as to not have it twice, and whether to add it behind a ? if there are no other options, or a & if there are other options already defined.

So in other words, what I want to know is does ngRoute provide methods to set parameters; not just read them? So I could do something like $routeParams.set("order", "amplitude").


回答1:


If you want to change the URL, you should do this through the $location service.

Specifically the $location.search(search, paramValue) will allow you to change the query string values.

I made a plunk that demonstrates both using HTML5 mode and changing the $location using these functions. It can be found here. In order to see the URL change, click the pop-out button .


You don't have to do the string parsing yourself. AngularJS will also allow you (with the same function) to query the currently set parameters. So it's a matter of querying all the URL values, changing the one for which filter you're changing, and then setting the values back.

This is what the second button in the example demonstrates. Even though the first button will only set its own value (and remove the others), the second button will keep all other items as well.


The relevant code:

var values = $location.search();
values.orderThatsUpdating = newOrderValue;
$location.search(values);


来源:https://stackoverflow.com/questions/34700599/can-i-set-a-parameter-using-ngroute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!