如果匹配值,AngularJS 在加载时更改单个 URL 参数 [英] AngularJS change single URL parameter on load if it matches a value

查看:13
本文介绍了如果匹配值,AngularJS 在加载时更改单个 URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个网络应用程序,当您浏览网站时,该应用程序会将参数传递给视图.这些参数由用户过滤器设置.

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.

我一直在使用 $location.search({ type: "blue" }) 但我意识到如果 url/视图中还有其他参数,这些参数会被删除仅适用于使用该代码设置的那个.

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.

基本上,在某些视图上,如果 type 参数是 all,则需要更改为 blue,而在其他视图中,则需要更改红色.

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.

不幸的是,这个参数是由当前应用的过滤器在链接中设置的,所以并不像更改href那么简单.

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.

您可以在此示例中看到,当来自 blue 的视图时,我正在尝试将只能设置为 red 的视图更改为 red 是使用路径数组设置的(并在链接中).

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"});
   }
 }

(这是在 $rootScope.$on("$locationChangeStart", function (event, newUrl, oldUrl) 函数内)

如果有一种方法可以改变这样的参数而不改变任何其他参数,那就太棒了!

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 :)

为了匿名将东西改成颜色,我没生气:)

推荐答案

如果你想设置单个搜索参数你可以这样做

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

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

这篇关于如果匹配值,AngularJS 在加载时更改单个 URL 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆