2 * @license AngularJS v1.2.5
3 * (c) 2010-2014 Google, Inc. http://angularjs.org
6 (function(window, angular, undefined) {'use strict';
15 * The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
18 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
20 * {@installModule route}
22 * <div doc-module-components="ngRoute"></div>
24 /* global -ngRouteModule */
25 var ngRouteModule = angular.module('ngRoute', ['ng']).
26 provider('$route', $RouteProvider);
30 * @name ngRoute.$routeProvider
35 * Used for configuring routes.
38 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
41 * Requires the {@link ngRoute `ngRoute`} module to be installed.
43 function $RouteProvider(){
44 function inherit(parent, extra) {
45 return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra);
52 * @name ngRoute.$routeProvider#when
53 * @methodOf ngRoute.$routeProvider
55 * @param {string} path Route path (matched against `$location.path`). If `$location.path`
56 * contains redundant trailing slash or is missing one, the route will still match and the
57 * `$location.path` will be updated to add or drop the trailing slash to exactly match the
60 * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
61 * to the next slash are matched and stored in `$routeParams` under the given `name`
62 * when the route matches.
63 * * `path` can contain named groups starting with a colon and ending with a star:
64 * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
65 * when the route matches.
66 * * `path` can contain optional named groups with a question mark: e.g.`:name?`.
68 * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
69 * `/color/brown/largecode/code/with/slashs/edit` and extract:
72 * * `largecode: code/with/slashs`.
75 * @param {Object} route Mapping information to be assigned to `$route.current` on route
80 * - `controller` – `{(string|function()=}` – Controller fn that should be associated with
81 * newly created scope or the name of a {@link angular.Module#controller registered
82 * controller} if passed as a string.
83 * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be
84 * published to scope under the `controllerAs` name.
85 * - `template` – `{string=|function()=}` – html template as a string or a function that
86 * returns an html template as a string which should be used by {@link
87 * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
88 * This property takes precedence over `templateUrl`.
90 * If `template` is a function, it will be called with the following parameters:
92 * - `{Array.<Object>}` - route parameters extracted from the current
93 * `$location.path()` by applying the current route
95 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
96 * template that should be used by {@link ngRoute.directive:ngView ngView}.
98 * If `templateUrl` is a function, it will be called with the following parameters:
100 * - `{Array.<Object>}` - route parameters extracted from the current
101 * `$location.path()` by applying the current route
103 * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
104 * be injected into the controller. If any of these dependencies are promises, the router
105 * will wait for them all to be resolved or one to be rejected before the controller is
107 * If all the promises are resolved successfully, the values of the resolved promises are
108 * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
109 * fired. If any of the promises are rejected the
110 * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object
113 * - `key` – `{string}`: a name of a dependency to be injected into the controller.
114 * - `factory` - `{string|function}`: If `string` then it is an alias for a service.
115 * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
116 * and the return value is treated as the dependency. If the result is a promise, it is
117 * resolved before its value is injected into the controller. Be aware that
118 * `ngRoute.$routeParams` will still refer to the previous route within these resolve
119 * functions. Use `$route.current.params` to access the new route parameters, instead.
121 * - `redirectTo` – {(string|function())=} – value to update
122 * {@link ng.$location $location} path with and trigger route redirection.
124 * If `redirectTo` is a function, it will be called with the following parameters:
126 * - `{Object.<string>}` - route parameters extracted from the current
127 * `$location.path()` by applying the current route templateUrl.
128 * - `{string}` - current `$location.path()`
129 * - `{Object}` - current `$location.search()`
131 * The custom `redirectTo` function is expected to return a string which will be used
132 * to update `$location.path()` and `$location.search()`.
134 * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()`
135 * or `$location.hash()` changes.
137 * If the option is set to `false` and url in the browser changes, then
138 * `$routeUpdate` event is broadcasted on the root scope.
140 * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
142 * If the option is set to `true`, then the particular route can be matched without being
145 * @returns {Object} self
148 * Adds a new route definition to the `$route` service.
150 this.when = function(path, route) {
151 routes[path] = angular.extend(
152 {reloadOnSearch: true},
154 path && pathRegExp(path, route)
157 // create redirection for trailing slashes
159 var redirectPath = (path[path.length-1] == '/')
160 ? path.substr(0, path.length-1)
163 routes[redirectPath] = angular.extend(
165 pathRegExp(redirectPath, route)
173 * @param path {string} path
174 * @param opts {Object} options
178 * Normalizes the given path, returning a regular expression
179 * and the original path.
181 * Inspired by pathRexp in visionmedia/express/lib/utils.js.
183 function pathRegExp(path, opts) {
184 var insensitive = opts.caseInsensitiveMatch,
189 keys = ret.keys = [];
192 .replace(/([().])/g, '\\$1')
193 .replace(/(\/)?:(\w+)([\?|\*])?/g, function(_, slash, key, option){
194 var optional = option === '?' ? option : null;
195 var star = option === '*' ? option : null;
196 keys.push({ name: key, optional: !!optional });
199 + (optional ? '' : slash)
201 + (optional ? slash : '')
202 + (star && '(.+?)' || '([^/]+)')
207 .replace(/([\/$\*])/g, '\\$1');
209 ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
215 * @name ngRoute.$routeProvider#otherwise
216 * @methodOf ngRoute.$routeProvider
219 * Sets route definition that will be used on route change when no other route definition
222 * @param {Object} params Mapping information to be assigned to `$route.current`.
223 * @returns {Object} self
225 this.otherwise = function(params) {
226 this.when(null, params);
231 this.$get = ['$rootScope',
239 function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) {
243 * @name ngRoute.$route
244 * @requires $location
245 * @requires $routeParams
247 * @property {Object} current Reference to the current route definition.
248 * The route definition contains:
250 * - `controller`: The controller constructor as define in route definition.
251 * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
252 * controller instantiation. The `locals` contain
253 * the resolved values of the `resolve` map. Additionally the `locals` also contain:
255 * - `$scope` - The current route scope.
256 * - `$template` - The current route template HTML.
258 * @property {Array.<Object>} routes Array of all configured routes.
261 * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
262 * It watches `$location.url()` and tries to map the path to an existing route definition.
264 * Requires the {@link ngRoute `ngRoute`} module to be installed.
266 * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
268 * The `$route` service is typically used in conjunction with the
269 * {@link ngRoute.directive:ngView `ngView`} directive and the
270 * {@link ngRoute.$routeParams `$routeParams`} service.
273 This example shows how changing the URL hash causes the `$route` to match a route against the
274 URL, and the `ngView` pulls in the partial.
276 Note that this example is using {@link ng.directive:script inlined templates}
277 to get it working on jsfiddle as well.
279 <example module="ngViewExample" deps="angular-route.js">
280 <file name="index.html">
281 <div ng-controller="MainCntl">
283 <a href="Book/Moby">Moby</a> |
284 <a href="Book/Moby/ch/1">Moby: Ch1</a> |
285 <a href="Book/Gatsby">Gatsby</a> |
286 <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
287 <a href="Book/Scarlet">Scarlet Letter</a><br/>
292 <pre>$location.path() = {{$location.path()}}</pre>
293 <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
294 <pre>$route.current.params = {{$route.current.params}}</pre>
295 <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
296 <pre>$routeParams = {{$routeParams}}</pre>
300 <file name="book.html">
301 controller: {{name}}<br />
302 Book Id: {{params.bookId}}<br />
305 <file name="chapter.html">
306 controller: {{name}}<br />
307 Book Id: {{params.bookId}}<br />
308 Chapter Id: {{params.chapterId}}
311 <file name="script.js">
312 angular.module('ngViewExample', ['ngRoute'])
314 .config(function($routeProvider, $locationProvider) {
315 $routeProvider.when('/Book/:bookId', {
316 templateUrl: 'book.html',
317 controller: BookCntl,
319 // I will cause a 1 second delay
320 delay: function($q, $timeout) {
321 var delay = $q.defer();
322 $timeout(delay.resolve, 1000);
323 return delay.promise;
327 $routeProvider.when('/Book/:bookId/ch/:chapterId', {
328 templateUrl: 'chapter.html',
329 controller: ChapterCntl
332 // configure html5 to get links working on jsfiddle
333 $locationProvider.html5Mode(true);
336 function MainCntl($scope, $route, $routeParams, $location) {
337 $scope.$route = $route;
338 $scope.$location = $location;
339 $scope.$routeParams = $routeParams;
342 function BookCntl($scope, $routeParams) {
343 $scope.name = "BookCntl";
344 $scope.params = $routeParams;
347 function ChapterCntl($scope, $routeParams) {
348 $scope.name = "ChapterCntl";
349 $scope.params = $routeParams;
353 <file name="scenario.js">
354 it('should load and compile correct template', function() {
355 element('a:contains("Moby: Ch1")').click();
356 var content = element('.doc-example-live [ng-view]').text();
357 expect(content).toMatch(/controller\: ChapterCntl/);
358 expect(content).toMatch(/Book Id\: Moby/);
359 expect(content).toMatch(/Chapter Id\: 1/);
361 element('a:contains("Scarlet")').click();
362 sleep(2); // promises are not part of scenario waiting
363 content = element('.doc-example-live [ng-view]').text();
364 expect(content).toMatch(/controller\: BookCntl/);
365 expect(content).toMatch(/Book Id\: Scarlet/);
373 * @name ngRoute.$route#$routeChangeStart
374 * @eventOf ngRoute.$route
375 * @eventType broadcast on root scope
377 * Broadcasted before a route change. At this point the route services starts
378 * resolving all of the dependencies needed for the route change to occurs.
379 * Typically this involves fetching the view template as well as any dependencies
380 * defined in `resolve` route property. Once all of the dependencies are resolved
381 * `$routeChangeSuccess` is fired.
383 * @param {Object} angularEvent Synthetic event object.
384 * @param {Route} next Future route information.
385 * @param {Route} current Current route information.
390 * @name ngRoute.$route#$routeChangeSuccess
391 * @eventOf ngRoute.$route
392 * @eventType broadcast on root scope
394 * Broadcasted after a route dependencies are resolved.
395 * {@link ngRoute.directive:ngView ngView} listens for the directive
396 * to instantiate the controller and render the view.
398 * @param {Object} angularEvent Synthetic event object.
399 * @param {Route} current Current route information.
400 * @param {Route|Undefined} previous Previous route information, or undefined if current is
401 * first route entered.
406 * @name ngRoute.$route#$routeChangeError
407 * @eventOf ngRoute.$route
408 * @eventType broadcast on root scope
410 * Broadcasted if any of the resolve promises are rejected.
412 * @param {Object} angularEvent Synthetic event object
413 * @param {Route} current Current route information.
414 * @param {Route} previous Previous route information.
415 * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
420 * @name ngRoute.$route#$routeUpdate
421 * @eventOf ngRoute.$route
422 * @eventType broadcast on root scope
425 * The `reloadOnSearch` property has been set to false, and we are reusing the same
426 * instance of the Controller.
429 var forceReload = false,
435 * @name ngRoute.$route#reload
436 * @methodOf ngRoute.$route
439 * Causes `$route` service to reload the current route even if
440 * {@link ng.$location $location} hasn't changed.
442 * As a result of that, {@link ngRoute.directive:ngView ngView}
443 * creates new scope, reinstantiates the controller.
447 $rootScope.$evalAsync(updateRoute);
451 $rootScope.$on('$locationChangeSuccess', updateRoute);
455 /////////////////////////////////////////////////////
458 * @param on {string} current url
459 * @param route {Object} route regexp to match the url against
463 * Check if the route matches the current url.
465 * Inspired by match in
466 * visionmedia/express/lib/router/router.js.
468 function switchRouteMatcher(on, route) {
469 var keys = route.keys,
472 if (!route.regexp) return null;
474 var m = route.regexp.exec(on);
477 for (var i = 1, len = m.length; i < len; ++i) {
478 var key = keys[i - 1];
480 var val = 'string' == typeof m[i]
481 ? decodeURIComponent(m[i])
485 params[key.name] = val;
491 function updateRoute() {
492 var next = parseRoute(),
493 last = $route.current;
495 if (next && last && next.$$route === last.$$route
496 && angular.equals(next.pathParams, last.pathParams)
497 && !next.reloadOnSearch && !forceReload) {
498 last.params = next.params;
499 angular.copy(last.params, $routeParams);
500 $rootScope.$broadcast('$routeUpdate', last);
501 } else if (next || last) {
503 $rootScope.$broadcast('$routeChangeStart', next, last);
504 $route.current = next;
506 if (next.redirectTo) {
507 if (angular.isString(next.redirectTo)) {
508 $location.path(interpolate(next.redirectTo, next.params)).search(next.params)
511 $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
520 var locals = angular.extend({}, next.resolve),
521 template, templateUrl;
523 angular.forEach(locals, function(value, key) {
524 locals[key] = angular.isString(value) ?
525 $injector.get(value) : $injector.invoke(value);
528 if (angular.isDefined(template = next.template)) {
529 if (angular.isFunction(template)) {
530 template = template(next.params);
532 } else if (angular.isDefined(templateUrl = next.templateUrl)) {
533 if (angular.isFunction(templateUrl)) {
534 templateUrl = templateUrl(next.params);
536 templateUrl = $sce.getTrustedResourceUrl(templateUrl);
537 if (angular.isDefined(templateUrl)) {
538 next.loadedTemplateUrl = templateUrl;
539 template = $http.get(templateUrl, {cache: $templateCache}).
540 then(function(response) { return response.data; });
543 if (angular.isDefined(template)) {
544 locals['$template'] = template;
546 return $q.all(locals);
549 // after route change
550 then(function(locals) {
551 if (next == $route.current) {
553 next.locals = locals;
554 angular.copy(next.params, $routeParams);
556 $rootScope.$broadcast('$routeChangeSuccess', next, last);
559 if (next == $route.current) {
560 $rootScope.$broadcast('$routeChangeError', next, last, error);
568 * @returns the current active route, by matching it against the URL
570 function parseRoute() {
573 angular.forEach(routes, function(route, path) {
574 if (!match && (params = switchRouteMatcher($location.path(), route))) {
575 match = inherit(route, {
576 params: angular.extend({}, $location.search(), params),
577 pathParams: params});
578 match.$$route = route;
581 // No route matched; fallback to "otherwise" route
582 return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
586 * @returns interpolation of the redirect path with the parameters
588 function interpolate(string, params) {
590 angular.forEach((string||'').split(':'), function(segment, i) {
592 result.push(segment);
594 var segmentMatch = segment.match(/(\w+)(.*)/);
595 var key = segmentMatch[1];
596 result.push(params[key]);
597 result.push(segmentMatch[2] || '');
601 return result.join('');
606 ngRouteModule.provider('$routeParams', $RouteParamsProvider);
611 * @name ngRoute.$routeParams
615 * The `$routeParams` service allows you to retrieve the current set of route parameters.
617 * Requires the {@link ngRoute `ngRoute`} module to be installed.
619 * The route parameters are a combination of {@link ng.$location `$location`}'s
620 * {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}.
621 * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
623 * In case of parameter name collision, `path` params take precedence over `search` params.
625 * The service guarantees that the identity of the `$routeParams` object will remain unchanged
626 * (but its properties will likely change) even when a route change occurs.
628 * Note that the `$routeParams` are only updated *after* a route change completes successfully.
629 * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
630 * Instead you can use `$route.current.params` to access the new route's parameters.
635 * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
636 * // Route: /Chapter/:chapterId/Section/:sectionId
639 * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
642 function $RouteParamsProvider() {
643 this.$get = function() { return {}; };
646 ngRouteModule.directive('ngView', ngViewFactory);
647 ngRouteModule.directive('ngView', ngViewFillContentFactory);
652 * @name ngRoute.directive:ngView
657 * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
658 * including the rendered template of the current route into the main layout (`index.html`) file.
659 * Every time the current route changes, the included view changes with it according to the
660 * configuration of the `$route` service.
662 * Requires the {@link ngRoute `ngRoute`} module to be installed.
665 * enter - animation is used to bring new content into the browser.
666 * leave - animation is used to animate existing content away.
668 * The enter and leave animation occur concurrently.
673 <example module="ngViewExample" deps="angular-route.js" animations="true">
674 <file name="index.html">
675 <div ng-controller="MainCntl as main">
677 <a href="Book/Moby">Moby</a> |
678 <a href="Book/Moby/ch/1">Moby: Ch1</a> |
679 <a href="Book/Gatsby">Gatsby</a> |
680 <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
681 <a href="Book/Scarlet">Scarlet Letter</a><br/>
683 <div class="view-animate-container">
684 <div ng-view class="view-animate"></div>
688 <pre>$location.path() = {{main.$location.path()}}</pre>
689 <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
690 <pre>$route.current.params = {{main.$route.current.params}}</pre>
691 <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre>
692 <pre>$routeParams = {{main.$routeParams}}</pre>
696 <file name="book.html">
698 controller: {{book.name}}<br />
699 Book Id: {{book.params.bookId}}<br />
703 <file name="chapter.html">
705 controller: {{chapter.name}}<br />
706 Book Id: {{chapter.params.bookId}}<br />
707 Chapter Id: {{chapter.params.chapterId}}
711 <file name="animations.css">
712 .view-animate-container {
714 height:100px!important;
717 border:1px solid black;
726 .view-animate.ng-enter, .view-animate.ng-leave {
727 -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
728 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
732 border-left:1px solid black;
742 .view-animate.ng-enter {
745 .view-animate.ng-enter.ng-enter-active {
748 .view-animate.ng-leave.ng-leave-active {
753 <file name="script.js">
754 angular.module('ngViewExample', ['ngRoute', 'ngAnimate'],
755 function($routeProvider, $locationProvider) {
756 $routeProvider.when('/Book/:bookId', {
757 templateUrl: 'book.html',
758 controller: BookCntl,
761 $routeProvider.when('/Book/:bookId/ch/:chapterId', {
762 templateUrl: 'chapter.html',
763 controller: ChapterCntl,
764 controllerAs: 'chapter'
767 // configure html5 to get links working on jsfiddle
768 $locationProvider.html5Mode(true);
771 function MainCntl($route, $routeParams, $location) {
772 this.$route = $route;
773 this.$location = $location;
774 this.$routeParams = $routeParams;
777 function BookCntl($routeParams) {
778 this.name = "BookCntl";
779 this.params = $routeParams;
782 function ChapterCntl($routeParams) {
783 this.name = "ChapterCntl";
784 this.params = $routeParams;
788 <file name="scenario.js">
789 it('should load and compile correct template', function() {
790 element('a:contains("Moby: Ch1")').click();
791 var content = element('.doc-example-live [ng-view]').text();
792 expect(content).toMatch(/controller\: ChapterCntl/);
793 expect(content).toMatch(/Book Id\: Moby/);
794 expect(content).toMatch(/Chapter Id\: 1/);
796 element('a:contains("Scarlet")').click();
797 content = element('.doc-example-live [ng-view]').text();
798 expect(content).toMatch(/controller\: BookCntl/);
799 expect(content).toMatch(/Book Id\: Scarlet/);
808 * @name ngRoute.directive:ngView#$viewContentLoaded
809 * @eventOf ngRoute.directive:ngView
810 * @eventType emit on the current ngView scope
812 * Emitted every time the ngView content is reloaded.
814 ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
815 function ngViewFactory( $route, $anchorScroll, $animate) {
820 transclude: 'element',
821 link: function(scope, $element, attr, ctrl, $transclude) {
824 autoScrollExp = attr.autoscroll,
825 onloadExp = attr.onload || '';
827 scope.$on('$routeChangeSuccess', update);
830 function cleanupLastView() {
832 currentScope.$destroy();
836 $animate.leave(currentElement);
837 currentElement = null;
842 var locals = $route.current && $route.current.locals,
843 template = locals && locals.$template;
846 var newScope = scope.$new();
847 var current = $route.current;
849 // Note: This will also link all children of ng-view that were contained in the original
850 // html. If that content contains controllers, ... they could pollute/change the scope.
851 // However, using ng-view on an element with additional content does not make sense...
852 // Note: We can't remove them in the cloneAttchFn of $transclude as that
853 // function is called before linking the content, which would apply child
854 // directives to non existing elements.
855 var clone = $transclude(newScope, function(clone) {
856 $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () {
857 if (angular.isDefined(autoScrollExp)
858 && (!autoScrollExp || scope.$eval(autoScrollExp))) {
865 currentElement = clone;
866 currentScope = current.scope = newScope;
867 currentScope.$emit('$viewContentLoaded');
868 currentScope.$eval(onloadExp);
877 // This directive is called during the $transclude call of the first `ngView` directive.
878 // It will replace and compile the content of the element with the loaded template.
879 // We need this directive so that the element content is already filled when
880 // the link function of another directive on the same element as ngView
882 ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
883 function ngViewFillContentFactory($compile, $controller, $route) {
887 link: function(scope, $element) {
888 var current = $route.current,
889 locals = current.locals;
891 $element.html(locals.$template);
893 var link = $compile($element.contents());
895 if (current.controller) {
896 locals.$scope = scope;
897 var controller = $controller(current.controller, locals);
898 if (current.controllerAs) {
899 scope[current.controllerAs] = controller;
901 $element.data('$ngControllerController', controller);
902 $element.children().data('$ngControllerController', controller);
911 })(window, window.angular);