Skip to content

Commit

Permalink
feat($route): when matching consider trailing slash as optional
Browse files Browse the repository at this point in the history
This makes for a much more flexible route matching:

- route /foo matches /foo and redirects /foo/ to /foo
- route /bar/ matches /bar/ and redirects /bar to /bar/

Closes angular#784
  • Loading branch information
IgorMinar committed Mar 20, 2012
1 parent ee5a535 commit a4fe51d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/service/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ function $RouteProvider(){
* @name angular.module.ng.$routeProvider#when
* @methodOf angular.module.ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.hash`)
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redudant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exacly match the
* route definition.
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
Expand Down Expand Up @@ -57,6 +60,16 @@ function $RouteProvider(){
var routeDef = routes[path];
if (!routeDef) routeDef = routes[path] = {reloadOnSearch: true};
if (route) extend(routeDef, route); // TODO(im): what the heck? merge two route definitions?

// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';

routes[redirectPath] = {redirectTo: path};
}

return routeDef;
};

Expand Down
30 changes: 30 additions & 0 deletions test/service/routeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,36 @@ describe('$route', function() {
});


it('should match route with and without trailing slash', function() {
module(function($routeProvider){
$routeProvider.when('/foo', {template: 'foo.html'});
$routeProvider.when('/bar/', {template: 'bar.html'});
});

inject(function($route, $location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.template).toBe('foo.html');

$location.path('/foo/');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.template).toBe('foo.html');

$location.path('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar/');
expect($route.current.template).toBe('bar.html');

$location.path('/bar/');
$rootScope.$digest();
expect($location.path()).toBe('/bar/');
expect($route.current.template).toBe('bar.html');
});
});


describe('redirection', function() {
it('should support redirection via redirectTo property by updating $location', function() {
module(function($routeProvider) {
Expand Down

0 comments on commit a4fe51d

Please sign in to comment.