处理尾随斜线在angularUI路由器 [英] Handling trailing slashes in angularUI router
问题描述
它已经好几个小时,我开始在这个问题上工作,我似乎无法让我的头解决各地。
It's been hours since I started working on this problem and I can't seem to get my head around the solution.
我有可能会导致用户实际上是在输入网址的应用程序。在这种情况下,是不是很难相信,用户可以输入尾随斜线。例如,
I have an app that may result in users actually typing in the URL. In such cases it is not hard to believe that user might enter a trailing slash. For example,
www.xxx.com/users/2和www.xxx.com/edit/company/123
www.xxx.com/users/2 and www.xxx.com/edit/company/123
应该一样对待
www.xxx.com/users/2/和www.xxx.com/edit/company/123 /
www.xxx.com/users/2/ and www.xxx.com/edit/company/123/
这仅需要对客户端处理URL路由完成。我没有兴趣在资源/ API调用处理尾随斜线。我只在处理尾随感兴趣削减在浏览器中。
This only needs to done for handling URL routing on the client side. I am not interested in handling trailing slashes in resource/API calls. I am only interested in handling trailing slashed in the browser.
于是我研究,发现在网络上不是很多答案。他们中的大多数导致我角UI路由器的常见问题解答部分。
So I researched and found not many answers on the net. Most of them led me to the FAQ section of angular-ui router.
<一个href=\"https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions\">https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions
在这里,他们告诉我们写的规则,这是我想做的事,但它似乎并不奏效,或者我做错了。
Here they tell us to write a rule, which is what I want to do, but it doesn't seem to be working, or maybe I am doing it wrong.
在此处,我已经加入我的code中的plunkr。
Here's the plunkr where I have added my code.
http://plnkr.co/edit/fD9q7L?p=$p$pview
基本上,我已经加入这个我的配置中,code的其余部分是pretty很多基本的东西。
Basically, I have added this to my config, the rest of the code is pretty much the basic stuff.
$urlRouterProvider.rule(function($injector, $location) {
//if last charcter is a slash, return the same url without the slash
if($location.$$url[length-1] === '/') {
return $location.$$url.substr(0,$location.$$url.length - 2);
} else {
//if the last char is not a trailing slash, do nothing
return $location.$$url;
}
});
基本上,我想使后面的斜杠可选的,也就是说,它的地址栏上presence与否应该对加载的状态没有影响。
Basically, I want to make the trailing slash optional, ie it's presence or absence on the address bar should have no effect on the state loaded.
感谢您的帮助!
推荐答案
有对工作 plunker <链接/ A>
There is a link to working plunker
这是更新的规则定义:
$urlRouterProvider.rule(function($injector, $location) {
var path = $location.path();
var hasTrailingSlash = path[path.length-1] === '/';
if(hasTrailingSlash) {
//if last charcter is a slash, return the same url without the slash
var newPath = path.substr(0, path.length - 1);
return newPath;
}
});
和这些链接现在将正常工作:
And these links will now work properly:
<ul class="nav">
<li><a ui-sref="route1">Route 1</a></li>
<li><a ui-sref="route2">Route 2</a></li>
<li><a href="#/route1/">#/route1/</a></li>
<li><a href="#/route2/">#/route2/</a></li>
<li><a href="#/route1" >#/route1</a></li>
<li><a href="#/route2" >#/route2</a></li>
</ul>
的魔法可以定义是这样的:做回改变的值,如果有变化...否则什么也不做...... 的的见例如
这篇关于处理尾随斜线在angularUI路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!