forked from angular/angular.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.js
416 lines (370 loc) · 13.5 KB
/
route.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
'use strict';
/**
* @ngdoc object
* @name angular.module.ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link angular.module.ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name angular.module.ng.$routeProvider#when
* @methodOf angular.module.ng.$routeProvider
*
* @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.
*
* Object properties:
*
* - `controller` – `{function()=}` – Controller fn that should be associated with newly
* created scope.
* - `template` – `{string=}` – path to an html template that should be used by
* {@link angular.module.ng.$compileProvider.directive.ngView ngView} or
* {@link angular.module.ng.$compileProvider.directive.ngInclude ngInclude} directives.
* - `redirectTo` – {(string|function())=} – value to update
* {@link angular.module.ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route template.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route, constraints) {
var regex;
routes[path] = extend({reloadOnSearch: true}, route, {
routeParams:extractParams(path, constraints)
});
routes[path].regex = regex = getRouteMatchingRegex(path, routes[path].routeParams);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {
redirectTo: path,
routeParams: routes[path].routeParams
};
routes[redirectPath].regex = (regex[regex.length - 2] == '/')
? regex.substr(0, regex.length - 2) + '$'
: regex.substr(0, regex.length - 1) + '/$';
}
return this;
};
/**
* @ngdoc method
* @name angular.module.ng.$routeProvider#otherwise
* @methodOf angular.module.ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
var shortcuts = this.shortcuts = {
"int": {
regex: "\\d+?",
parse: function(value) { return parseInt(value, 10); }
},
"float": {
regex: "\\d+\\.\\d+?",
parse: function(value) { return parseFloat(value); }
},
"bool": {
regex: "true|false",
parse: function(value) { return angular.lowercase(value) === "true"; }
},
"string": {
regex: "\\w+?"
}
};
this.$get = ['$rootScope', '$location', '$routeParams',
function( $rootScope, $location, $routeParams) {
/**
* @ngdoc object
* @name angular.module.ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link angular.module.ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link angular.module.ng.$compileProvider.directive.ngView ngView}
* directive and the {@link angular.module.ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link angular.module.ng.$compileProvider.directive.script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.template = {{$route.current.template}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
template: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
template: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name angular.module.ng.$route#$beforeRouteChange
* @eventOf angular.module.ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name angular.module.ng.$route#$afterRouteChange
* @eventOf angular.module.ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route change.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*/
/**
* @ngdoc event
* @name angular.module.ng.$route#$routeUpdate
* @eventOf angular.module.ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var matcher = switchRouteMatcher,
dirty = 0,
forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name angular.module.ng.$route#reload
* @methodOf angular.module.ng.$route
*
* @description
* Causes `$route` service to reload theR current route even if
* {@link angular.module.ng.$location $location} hasn't changed.
*
* As a result of that, {@link angular.module.ng.$compileProvider.directive.ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
dirty++;
forceReload = true;
}
};
$rootScope.$watch(function() { return dirty + $location.url(); }, updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
var dst = {};
var match = routes[when].regex && on.match(new RegExp(routes[when].regex));
if (match) {
forEach(routes[when].routeParams, function(param, index) {
if (shortcuts[param[1]] && isFunction(shortcuts[param[1]].parse)) {
dst[param[0]] = shortcuts[param[1]].parse(match[index + 1]);
} else {
dst[param[0]] = match[index + 1];
}
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$route === last.$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$beforeRouteChange', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
} else {
copy(next.params, $routeParams);
}
}
$rootScope.$broadcast('$afterRouteChange', next, last);
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = matcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
function extractParams(when, constraints) {
constraints = constraints || {};
if (when == null)
return [];
var params = [];
forEach(when.split(/\W/), function(param) {
if (param && when.match(new RegExp(":" + param + "(\\W|$)"))) {
if (constraints[param] && isString(constraints[param])) {
params.push([param, constraints[param]]);
} else {
params.push([param]);
}
}
});
return params;
}
function getRouteMatchingRegex(when, params) {
if (when == null)
return;
var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
paramRegExp;
forEach(params, function(param) {
if (param[1]) {
paramRegExp = "(" + (shortcuts[param[1]] && shortcuts[param[1]].regex || param[1]) + ")$1";
} else {
paramRegExp = "([^\\/]*)$1";
}
regex = regex.replace(new RegExp(":" + param[0] + "([\\W])"), paramRegExp);
});
return regex;
}
}