自从我开始解决这个问题已经有几个小时了,我似乎无法解决这个问题。
我有一个可能会导致用户实际输入URL的应用程序。在这种情况下,不难相信用户可能会输入斜杠。例如,
www.example.com/users/2 and www.example.com/edit/company/123
应该与
www.example.com/users/2/ and www.example.com/edit/company/123/
只需在客户端处理URL路由即可。我对处理资源/ API调用中的尾部斜杠不感兴趣。我只对处理浏览器中的斜线感兴趣。
因此,我研究并在网上找不到很多答案。他们中的大多数将我带到了angular-ui路由器的FAQ部分。
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions
他们在这里告诉我们写一条规则,这是我想做的,但是它似乎没有用,或者我做错了。
这是我添加代码的代码库。
http://plnkr.co/edit/fD9q7L?p=preview
我已将此添加到配置中,其余代码几乎是基本内容。
$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;
}
});
基本上,我想使斜杠为可选,即地址栏上是否存在斜杠对加载的状态没有影响。
最佳答案
有一个指向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;
}
});
这些链接现在将正常工作:
<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>
魔术可以这样定义:如果有更改,请返回更改的值...否则不执行任何操作... see example
关于angularjs - 在有 Angular UI路由器中处理尾部斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24420578/