Skip to content

Commit cb8b751

Browse files
committed
Ensuring stable sort of route rules used for matching URLs.
1 parent 87f10df commit cb8b751

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

Diff for: src/urlRouter.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
6464
*/
6565
this.rule = function (rule) {
6666
if (!isFunction(rule)) throw new Error("'rule' must be a function");
67+
rule.position = rules.length;
6768
rules.push(rule);
6869
return this;
6970
};
@@ -304,11 +305,12 @@ function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
304305
listener = listener || $rootScope.$on('$locationChangeSuccess', update);
305306
return listener;
306307
}
307-
308+
308309
rules.sort(function(ruleA, ruleB) {
309310
var aLength = ruleA.prefix ? ruleA.prefix.length : 0;
310311
var bLength = ruleB.prefix ? ruleB.prefix.length : 0;
311-
return bLength - aLength;
312+
var lengthDiff = bLength - aLength;
313+
return lengthDiff !== 0 ? lengthDiff : ruleA.position - ruleB.position;
312314
});
313315

314316
if (!interceptDeferred) listen();

Diff for: test/urlRouterSpec.js

+32-2
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,31 @@ describe("UrlRouter", function () {
5959
match = ['/foo/bar', $match];
6060
}).when('/bar', function($match) {
6161
match = ['/bar', $match];
62-
});
62+
}).when('/', function() {
63+
match = '/home';
64+
}).when('/abc', function() {
65+
match = '/abc/step1';
66+
}).when('/abc', function() {
67+
match = '/abc/step2';
68+
}).when('/defg', function() {
69+
match = '/defg';
70+
}).when('/hij', function() {
71+
match = '/hij/step1';
72+
}).when('/hij', function() {
73+
match = '/hij/step2';
74+
}).when('/hij', function() {
75+
match = '/hij/step3';
76+
}).when('/hij', function() {
77+
match = '/hij/step4';
78+
}).when('/klmno', function() {
79+
match = '/klmno/step1';
80+
}).when('/klmno', function() {
81+
match = '/klmno/step2';
82+
}).when('/pqr', function() {
83+
match = '/pqr/step1';
84+
}).when('/pqr', function() {
85+
match = '/pqr/step2';}
86+
);
6387
});
6488

6589
module('ui.router.router', 'ui.router.router.test');
@@ -84,6 +108,12 @@ describe("UrlRouter", function () {
84108
expect(match[0]).toBe("/foo/:param");
85109
expect(match[1]).toEqual({param: 'baz'});
86110
});
111+
112+
it('should default to the first rule defined for same url', function() {
113+
location.path('/hij');
114+
scope.$emit('$locationChangeSuccess');
115+
expect(match).toBe('/hij/step1');
116+
});
87117

88118
it("should execute rewrite rules", function () {
89119
location.path("/foo");
@@ -261,4 +291,4 @@ describe("UrlRouter", function () {
261291
});
262292
});
263293

264-
});
294+
});

0 commit comments

Comments
 (0)