Skip to content

Commit fb3e027

Browse files
committed
Merge pull request #296 from Demeterr/keep-otherwise-last
Keep $urlRouterProvider.otherwise() handling last (was #281).
2 parents f0ce297 + ea5dff7 commit fb3e027

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

src/urlRouter.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,22 @@ function $UrlRouterProvider( $urlMatcherFactory) {
8686
this.$get =
8787
[ '$location', '$rootScope', '$injector',
8888
function ($location, $rootScope, $injector) {
89-
if (otherwise) rules.push(otherwise);
90-
9189
// TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
9290
function update() {
93-
var n=rules.length, i, handled;
94-
for (i=0; i<n; i++) {
95-
handled = rules[i]($injector, $location);
91+
function check(rule) {
92+
var handled = rule($injector, $location);
9693
if (handled) {
9794
if (isString(handled)) $location.replace().url(handled);
98-
break;
95+
return true;
9996
}
97+
return false;
98+
}
99+
var n=rules.length, i;
100+
for (i=0; i<n; i++) {
101+
if (check(rules[i])) return;
100102
}
103+
// always check otherwise last to allow dynamic updates to the set of rules
104+
if (otherwise) check(otherwise);
101105
}
102106

103107
$rootScope.$on('$locationChangeSuccess', update);

test/urlRouterSpec.js

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ describe("UrlRouter", function () {
77
$urp = $urlRouterProvider;
88

99
$urp.rule(function ($injector, $location) {
10-
return $location.path().replace('baz', 'b4z');
10+
var path = $location.path();
11+
if (!/baz/.test(path)) return false;
12+
return path.replace('baz', 'b4z');
1113
}).when('/foo/:param', function($match) {
1214
match = ['/foo/:param', $match];
1315
}).when('/bar', function($match) {
1416
match = ['/bar', $match];
15-
}).when('/:param', function($match) {
16-
match = ['/:param', $match];
1717
});
1818
});
1919

@@ -45,6 +45,22 @@ describe("UrlRouter", function () {
4545
scope.$emit("$locationChangeSuccess");
4646
expect(location.path()).toBe("/b4z");
4747
});
48+
49+
it("should keep otherwise last", function () {
50+
$urp.otherwise('/otherwise');
51+
52+
location.path("/lastrule");
53+
scope.$emit("$locationChangeSuccess");
54+
expect(location.path()).toBe("/otherwise");
55+
56+
$urp.when('/lastrule', function($match) {
57+
match = ['/lastrule', $match];
58+
});
59+
60+
location.path("/lastrule");
61+
scope.$emit("$locationChangeSuccess");
62+
expect(location.path()).toBe("/lastrule");
63+
});
4864
});
4965

50-
});
66+
});

0 commit comments

Comments
 (0)