angularjs - Handling trailing slashes in angularUI router -
it's been hours since started working on problem , can't seem head around solution.
i have app may result in users typing in url. in such cases not hard believe user might enter trailing slash. example,
www.example.com/users/2 , www.example.com/edit/company/123
should treated same as
www.example.com/users/2/ , www.example.com/edit/company/123/
this needs done handling url routing on client side. not interested in handling trailing slashes in resource/api calls. interested in handling trailing slashed in browser.
so researched , found not many answers on net. of them led me faq section of angular-ui router.
https://github.com/angular-ui/ui-router/wiki/frequently-asked-questions
here tell write rule, want do, doesn't seem working, or maybe doing wrong.
here's plunkr have added code.
http://plnkr.co/edit/fd9q7l?p=preview
i have added config, rest of code pretty basic stuff.
$urlrouterprovider.rule(function($injector, $location) { //if last charcter slash, return same url without slash if($location.$$url[length-1] === '/') { return $location.$$url.substr(0,$location.$$url.length - 2); } else { //if last char not trailing slash, nothing return $location.$$url; } });
basically, want make trailing slash optional, ie it's presence or absence on address bar should have no effect on state loaded.
there link working plunker
and updated rule definition:
$urlrouterprovider.rule(function($injector, $location) { var path = $location.path(); var hastrailingslash = path[path.length-1] === '/'; if(hastrailingslash) { //if last charcter slash, return same url without slash var newpath = path.substr(0, path.length - 1); return newpath; } });
and these links 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>
the magic defined this: return changed value if there change... otherwise nothing... see example
Comments
Post a Comment