angular-route.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. /**
  2. * @license AngularJS v1.6.2
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular) {'use strict';
  7. /* global shallowCopy: true */
  8. /**
  9. * Creates a shallow copy of an object, an array or a primitive.
  10. *
  11. * Assumes that there are no proto properties for objects.
  12. */
  13. function shallowCopy(src, dst) {
  14. if (isArray(src)) {
  15. dst = dst || [];
  16. for (var i = 0, ii = src.length; i < ii; i++) {
  17. dst[i] = src[i];
  18. }
  19. } else if (isObject(src)) {
  20. dst = dst || {};
  21. for (var key in src) {
  22. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  23. dst[key] = src[key];
  24. }
  25. }
  26. }
  27. return dst || src;
  28. }
  29. /* global shallowCopy: false */
  30. // `isArray` and `isObject` are necessary for `shallowCopy()` (included via `src/shallowCopy.js`).
  31. // They are initialized inside the `$RouteProvider`, to ensure `window.angular` is available.
  32. var isArray;
  33. var isObject;
  34. var isDefined;
  35. var noop;
  36. /**
  37. * @ngdoc module
  38. * @name ngRoute
  39. * @description
  40. *
  41. * # ngRoute
  42. *
  43. * The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
  44. *
  45. * ## Example
  46. * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
  47. *
  48. *
  49. * <div doc-module-components="ngRoute"></div>
  50. */
  51. /* global -ngRouteModule */
  52. var ngRouteModule = angular.
  53. module('ngRoute', []).
  54. provider('$route', $RouteProvider).
  55. // Ensure `$route` will be instantiated in time to capture the initial `$locationChangeSuccess`
  56. // event (unless explicitly disabled). This is necessary in case `ngView` is included in an
  57. // asynchronously loaded template.
  58. run(instantiateRoute);
  59. var $routeMinErr = angular.$$minErr('ngRoute');
  60. var isEagerInstantiationEnabled;
  61. /**
  62. * @ngdoc provider
  63. * @name $routeProvider
  64. * @this
  65. *
  66. * @description
  67. *
  68. * Used for configuring routes.
  69. *
  70. * ## Example
  71. * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
  72. *
  73. * ## Dependencies
  74. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  75. */
  76. function $RouteProvider() {
  77. isArray = angular.isArray;
  78. isObject = angular.isObject;
  79. isDefined = angular.isDefined;
  80. noop = angular.noop;
  81. function inherit(parent, extra) {
  82. return angular.extend(Object.create(parent), extra);
  83. }
  84. var routes = {};
  85. /**
  86. * @ngdoc method
  87. * @name $routeProvider#when
  88. *
  89. * @param {string} path Route path (matched against `$location.path`). If `$location.path`
  90. * contains redundant trailing slash or is missing one, the route will still match and the
  91. * `$location.path` will be updated to add or drop the trailing slash to exactly match the
  92. * route definition.
  93. *
  94. * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
  95. * to the next slash are matched and stored in `$routeParams` under the given `name`
  96. * when the route matches.
  97. * * `path` can contain named groups starting with a colon and ending with a star:
  98. * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
  99. * when the route matches.
  100. * * `path` can contain optional named groups with a question mark: e.g.`:name?`.
  101. *
  102. * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
  103. * `/color/brown/largecode/code/with/slashes/edit` and extract:
  104. *
  105. * * `color: brown`
  106. * * `largecode: code/with/slashes`.
  107. *
  108. *
  109. * @param {Object} route Mapping information to be assigned to `$route.current` on route
  110. * match.
  111. *
  112. * Object properties:
  113. *
  114. * - `controller` – `{(string|Function)=}` – Controller fn that should be associated with
  115. * newly created scope or the name of a {@link angular.Module#controller registered
  116. * controller} if passed as a string.
  117. * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
  118. * If present, the controller will be published to scope under the `controllerAs` name.
  119. * - `template` – `{(string|Function)=}` – html template as a string or a function that
  120. * returns an html template as a string which should be used by {@link
  121. * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
  122. * This property takes precedence over `templateUrl`.
  123. *
  124. * If `template` is a function, it will be called with the following parameters:
  125. *
  126. * - `{Array.<Object>}` - route parameters extracted from the current
  127. * `$location.path()` by applying the current route
  128. *
  129. * One of `template` or `templateUrl` is required.
  130. *
  131. * - `templateUrl` – `{(string|Function)=}` – path or function that returns a path to an html
  132. * template that should be used by {@link ngRoute.directive:ngView ngView}.
  133. *
  134. * If `templateUrl` is a function, it will be called with the following parameters:
  135. *
  136. * - `{Array.<Object>}` - route parameters extracted from the current
  137. * `$location.path()` by applying the current route
  138. *
  139. * One of `templateUrl` or `template` is required.
  140. *
  141. * - `resolve` - `{Object.<string, Function>=}` - An optional map of dependencies which should
  142. * be injected into the controller. If any of these dependencies are promises, the router
  143. * will wait for them all to be resolved or one to be rejected before the controller is
  144. * instantiated.
  145. * If all the promises are resolved successfully, the values of the resolved promises are
  146. * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
  147. * fired. If any of the promises are rejected the
  148. * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired.
  149. * For easier access to the resolved dependencies from the template, the `resolve` map will
  150. * be available on the scope of the route, under `$resolve` (by default) or a custom name
  151. * specified by the `resolveAs` property (see below). This can be particularly useful, when
  152. * working with {@link angular.Module#component components} as route templates.<br />
  153. * <div class="alert alert-warning">
  154. * **Note:** If your scope already contains a property with this name, it will be hidden
  155. * or overwritten. Make sure, you specify an appropriate name for this property, that
  156. * does not collide with other properties on the scope.
  157. * </div>
  158. * The map object is:
  159. *
  160. * - `key` – `{string}`: a name of a dependency to be injected into the controller.
  161. * - `factory` - `{string|Function}`: If `string` then it is an alias for a service.
  162. * Otherwise if function, then it is {@link auto.$injector#invoke injected}
  163. * and the return value is treated as the dependency. If the result is a promise, it is
  164. * resolved before its value is injected into the controller. Be aware that
  165. * `ngRoute.$routeParams` will still refer to the previous route within these resolve
  166. * functions. Use `$route.current.params` to access the new route parameters, instead.
  167. *
  168. * - `resolveAs` - `{string=}` - The name under which the `resolve` map will be available on
  169. * the scope of the route. If omitted, defaults to `$resolve`.
  170. *
  171. * - `redirectTo` – `{(string|Function)=}` – value to update
  172. * {@link ng.$location $location} path with and trigger route redirection.
  173. *
  174. * If `redirectTo` is a function, it will be called with the following parameters:
  175. *
  176. * - `{Object.<string>}` - route parameters extracted from the current
  177. * `$location.path()` by applying the current route templateUrl.
  178. * - `{string}` - current `$location.path()`
  179. * - `{Object}` - current `$location.search()`
  180. *
  181. * The custom `redirectTo` function is expected to return a string which will be used
  182. * to update `$location.url()`. If the function throws an error, no further processing will
  183. * take place and the {@link ngRoute.$route#$routeChangeError $routeChangeError} event will
  184. * be fired.
  185. *
  186. * Routes that specify `redirectTo` will not have their controllers, template functions
  187. * or resolves called, the `$location` will be changed to the redirect url and route
  188. * processing will stop. The exception to this is if the `redirectTo` is a function that
  189. * returns `undefined`. In this case the route transition occurs as though there was no
  190. * redirection.
  191. *
  192. * - `resolveRedirectTo` – `{Function=}` – a function that will (eventually) return the value
  193. * to update {@link ng.$location $location} URL with and trigger route redirection. In
  194. * contrast to `redirectTo`, dependencies can be injected into `resolveRedirectTo` and the
  195. * return value can be either a string or a promise that will be resolved to a string.
  196. *
  197. * Similar to `redirectTo`, if the return value is `undefined` (or a promise that gets
  198. * resolved to `undefined`), no redirection takes place and the route transition occurs as
  199. * though there was no redirection.
  200. *
  201. * If the function throws an error or the returned promise gets rejected, no further
  202. * processing will take place and the
  203. * {@link ngRoute.$route#$routeChangeError $routeChangeError} event will be fired.
  204. *
  205. * `redirectTo` takes precedence over `resolveRedirectTo`, so specifying both on the same
  206. * route definition, will cause the latter to be ignored.
  207. *
  208. * - `[reloadOnSearch=true]` - `{boolean=}` - reload route when only `$location.search()`
  209. * or `$location.hash()` changes.
  210. *
  211. * If the option is set to `false` and url in the browser changes, then
  212. * `$routeUpdate` event is broadcasted on the root scope.
  213. *
  214. * - `[caseInsensitiveMatch=false]` - `{boolean=}` - match routes without being case sensitive
  215. *
  216. * If the option is set to `true`, then the particular route can be matched without being
  217. * case sensitive
  218. *
  219. * @returns {Object} self
  220. *
  221. * @description
  222. * Adds a new route definition to the `$route` service.
  223. */
  224. this.when = function(path, route) {
  225. //copy original route object to preserve params inherited from proto chain
  226. var routeCopy = shallowCopy(route);
  227. if (angular.isUndefined(routeCopy.reloadOnSearch)) {
  228. routeCopy.reloadOnSearch = true;
  229. }
  230. if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
  231. routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
  232. }
  233. routes[path] = angular.extend(
  234. routeCopy,
  235. path && pathRegExp(path, routeCopy)
  236. );
  237. // create redirection for trailing slashes
  238. if (path) {
  239. var redirectPath = (path[path.length - 1] === '/')
  240. ? path.substr(0, path.length - 1)
  241. : path + '/';
  242. routes[redirectPath] = angular.extend(
  243. {redirectTo: path},
  244. pathRegExp(redirectPath, routeCopy)
  245. );
  246. }
  247. return this;
  248. };
  249. /**
  250. * @ngdoc property
  251. * @name $routeProvider#caseInsensitiveMatch
  252. * @description
  253. *
  254. * A boolean property indicating if routes defined
  255. * using this provider should be matched using a case insensitive
  256. * algorithm. Defaults to `false`.
  257. */
  258. this.caseInsensitiveMatch = false;
  259. /**
  260. * @param path {string} path
  261. * @param opts {Object} options
  262. * @return {?Object}
  263. *
  264. * @description
  265. * Normalizes the given path, returning a regular expression
  266. * and the original path.
  267. *
  268. * Inspired by pathRexp in visionmedia/express/lib/utils.js.
  269. */
  270. function pathRegExp(path, opts) {
  271. var insensitive = opts.caseInsensitiveMatch,
  272. ret = {
  273. originalPath: path,
  274. regexp: path
  275. },
  276. keys = ret.keys = [];
  277. path = path
  278. .replace(/([().])/g, '\\$1')
  279. .replace(/(\/)?:(\w+)(\*\?|[?*])?/g, function(_, slash, key, option) {
  280. var optional = (option === '?' || option === '*?') ? '?' : null;
  281. var star = (option === '*' || option === '*?') ? '*' : null;
  282. keys.push({ name: key, optional: !!optional });
  283. slash = slash || '';
  284. return ''
  285. + (optional ? '' : slash)
  286. + '(?:'
  287. + (optional ? slash : '')
  288. + (star && '(.+?)' || '([^/]+)')
  289. + (optional || '')
  290. + ')'
  291. + (optional || '');
  292. })
  293. .replace(/([/$*])/g, '\\$1');
  294. ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
  295. return ret;
  296. }
  297. /**
  298. * @ngdoc method
  299. * @name $routeProvider#otherwise
  300. *
  301. * @description
  302. * Sets route definition that will be used on route change when no other route definition
  303. * is matched.
  304. *
  305. * @param {Object|string} params Mapping information to be assigned to `$route.current`.
  306. * If called with a string, the value maps to `redirectTo`.
  307. * @returns {Object} self
  308. */
  309. this.otherwise = function(params) {
  310. if (typeof params === 'string') {
  311. params = {redirectTo: params};
  312. }
  313. this.when(null, params);
  314. return this;
  315. };
  316. /**
  317. * @ngdoc method
  318. * @name $routeProvider#eagerInstantiationEnabled
  319. * @kind function
  320. *
  321. * @description
  322. * Call this method as a setter to enable/disable eager instantiation of the
  323. * {@link ngRoute.$route $route} service upon application bootstrap. You can also call it as a
  324. * getter (i.e. without any arguments) to get the current value of the
  325. * `eagerInstantiationEnabled` flag.
  326. *
  327. * Instantiating `$route` early is necessary for capturing the initial
  328. * {@link ng.$location#$locationChangeStart $locationChangeStart} event and navigating to the
  329. * appropriate route. Usually, `$route` is instantiated in time by the
  330. * {@link ngRoute.ngView ngView} directive. Yet, in cases where `ngView` is included in an
  331. * asynchronously loaded template (e.g. in another directive's template), the directive factory
  332. * might not be called soon enough for `$route` to be instantiated _before_ the initial
  333. * `$locationChangeSuccess` event is fired. Eager instantiation ensures that `$route` is always
  334. * instantiated in time, regardless of when `ngView` will be loaded.
  335. *
  336. * The default value is true.
  337. *
  338. * **Note**:<br />
  339. * You may want to disable the default behavior when unit-testing modules that depend on
  340. * `ngRoute`, in order to avoid an unexpected request for the default route's template.
  341. *
  342. * @param {boolean=} enabled - If provided, update the internal `eagerInstantiationEnabled` flag.
  343. *
  344. * @returns {*} The current value of the `eagerInstantiationEnabled` flag if used as a getter or
  345. * itself (for chaining) if used as a setter.
  346. */
  347. isEagerInstantiationEnabled = true;
  348. this.eagerInstantiationEnabled = function eagerInstantiationEnabled(enabled) {
  349. if (isDefined(enabled)) {
  350. isEagerInstantiationEnabled = enabled;
  351. return this;
  352. }
  353. return isEagerInstantiationEnabled;
  354. };
  355. this.$get = ['$rootScope',
  356. '$location',
  357. '$routeParams',
  358. '$q',
  359. '$injector',
  360. '$templateRequest',
  361. '$sce',
  362. '$browser',
  363. function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce, $browser) {
  364. /**
  365. * @ngdoc service
  366. * @name $route
  367. * @requires $location
  368. * @requires $routeParams
  369. *
  370. * @property {Object} current Reference to the current route definition.
  371. * The route definition contains:
  372. *
  373. * - `controller`: The controller constructor as defined in the route definition.
  374. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
  375. * controller instantiation. The `locals` contain
  376. * the resolved values of the `resolve` map. Additionally the `locals` also contain:
  377. *
  378. * - `$scope` - The current route scope.
  379. * - `$template` - The current route template HTML.
  380. *
  381. * The `locals` will be assigned to the route scope's `$resolve` property. You can override
  382. * the property name, using `resolveAs` in the route definition. See
  383. * {@link ngRoute.$routeProvider $routeProvider} for more info.
  384. *
  385. * @property {Object} routes Object with all route configuration Objects as its properties.
  386. *
  387. * @description
  388. * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
  389. * It watches `$location.url()` and tries to map the path to an existing route definition.
  390. *
  391. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  392. *
  393. * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
  394. *
  395. * The `$route` service is typically used in conjunction with the
  396. * {@link ngRoute.directive:ngView `ngView`} directive and the
  397. * {@link ngRoute.$routeParams `$routeParams`} service.
  398. *
  399. * @example
  400. * This example shows how changing the URL hash causes the `$route` to match a route against the
  401. * URL, and the `ngView` pulls in the partial.
  402. *
  403. * <example name="$route-service" module="ngRouteExample"
  404. * deps="angular-route.js" fixBase="true">
  405. * <file name="index.html">
  406. * <div ng-controller="MainController">
  407. * Choose:
  408. * <a href="Book/Moby">Moby</a> |
  409. * <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  410. * <a href="Book/Gatsby">Gatsby</a> |
  411. * <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  412. * <a href="Book/Scarlet">Scarlet Letter</a><br/>
  413. *
  414. * <div ng-view></div>
  415. *
  416. * <hr />
  417. *
  418. * <pre>$location.path() = {{$location.path()}}</pre>
  419. * <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
  420. * <pre>$route.current.params = {{$route.current.params}}</pre>
  421. * <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
  422. * <pre>$routeParams = {{$routeParams}}</pre>
  423. * </div>
  424. * </file>
  425. *
  426. * <file name="book.html">
  427. * controller: {{name}}<br />
  428. * Book Id: {{params.bookId}}<br />
  429. * </file>
  430. *
  431. * <file name="chapter.html">
  432. * controller: {{name}}<br />
  433. * Book Id: {{params.bookId}}<br />
  434. * Chapter Id: {{params.chapterId}}
  435. * </file>
  436. *
  437. * <file name="script.js">
  438. * angular.module('ngRouteExample', ['ngRoute'])
  439. *
  440. * .controller('MainController', function($scope, $route, $routeParams, $location) {
  441. * $scope.$route = $route;
  442. * $scope.$location = $location;
  443. * $scope.$routeParams = $routeParams;
  444. * })
  445. *
  446. * .controller('BookController', function($scope, $routeParams) {
  447. * $scope.name = 'BookController';
  448. * $scope.params = $routeParams;
  449. * })
  450. *
  451. * .controller('ChapterController', function($scope, $routeParams) {
  452. * $scope.name = 'ChapterController';
  453. * $scope.params = $routeParams;
  454. * })
  455. *
  456. * .config(function($routeProvider, $locationProvider) {
  457. * $routeProvider
  458. * .when('/Book/:bookId', {
  459. * templateUrl: 'book.html',
  460. * controller: 'BookController',
  461. * resolve: {
  462. * // I will cause a 1 second delay
  463. * delay: function($q, $timeout) {
  464. * var delay = $q.defer();
  465. * $timeout(delay.resolve, 1000);
  466. * return delay.promise;
  467. * }
  468. * }
  469. * })
  470. * .when('/Book/:bookId/ch/:chapterId', {
  471. * templateUrl: 'chapter.html',
  472. * controller: 'ChapterController'
  473. * });
  474. *
  475. * // configure html5 to get links working on jsfiddle
  476. * $locationProvider.html5Mode(true);
  477. * });
  478. *
  479. * </file>
  480. *
  481. * <file name="protractor.js" type="protractor">
  482. * it('should load and compile correct template', function() {
  483. * element(by.linkText('Moby: Ch1')).click();
  484. * var content = element(by.css('[ng-view]')).getText();
  485. * expect(content).toMatch(/controller: ChapterController/);
  486. * expect(content).toMatch(/Book Id: Moby/);
  487. * expect(content).toMatch(/Chapter Id: 1/);
  488. *
  489. * element(by.partialLinkText('Scarlet')).click();
  490. *
  491. * content = element(by.css('[ng-view]')).getText();
  492. * expect(content).toMatch(/controller: BookController/);
  493. * expect(content).toMatch(/Book Id: Scarlet/);
  494. * });
  495. * </file>
  496. * </example>
  497. */
  498. /**
  499. * @ngdoc event
  500. * @name $route#$routeChangeStart
  501. * @eventType broadcast on root scope
  502. * @description
  503. * Broadcasted before a route change. At this point the route services starts
  504. * resolving all of the dependencies needed for the route change to occur.
  505. * Typically this involves fetching the view template as well as any dependencies
  506. * defined in `resolve` route property. Once all of the dependencies are resolved
  507. * `$routeChangeSuccess` is fired.
  508. *
  509. * The route change (and the `$location` change that triggered it) can be prevented
  510. * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
  511. * for more details about event object.
  512. *
  513. * @param {Object} angularEvent Synthetic event object.
  514. * @param {Route} next Future route information.
  515. * @param {Route} current Current route information.
  516. */
  517. /**
  518. * @ngdoc event
  519. * @name $route#$routeChangeSuccess
  520. * @eventType broadcast on root scope
  521. * @description
  522. * Broadcasted after a route change has happened successfully.
  523. * The `resolve` dependencies are now available in the `current.locals` property.
  524. *
  525. * {@link ngRoute.directive:ngView ngView} listens for the directive
  526. * to instantiate the controller and render the view.
  527. *
  528. * @param {Object} angularEvent Synthetic event object.
  529. * @param {Route} current Current route information.
  530. * @param {Route|Undefined} previous Previous route information, or undefined if current is
  531. * first route entered.
  532. */
  533. /**
  534. * @ngdoc event
  535. * @name $route#$routeChangeError
  536. * @eventType broadcast on root scope
  537. * @description
  538. * Broadcasted if a redirection function fails or any redirection or resolve promises are
  539. * rejected.
  540. *
  541. * @param {Object} angularEvent Synthetic event object
  542. * @param {Route} current Current route information.
  543. * @param {Route} previous Previous route information.
  544. * @param {Route} rejection The thrown error or the rejection reason of the promise. Usually
  545. * the rejection reason is the error that caused the promise to get rejected.
  546. */
  547. /**
  548. * @ngdoc event
  549. * @name $route#$routeUpdate
  550. * @eventType broadcast on root scope
  551. * @description
  552. * The `reloadOnSearch` property has been set to false, and we are reusing the same
  553. * instance of the Controller.
  554. *
  555. * @param {Object} angularEvent Synthetic event object
  556. * @param {Route} current Current/previous route information.
  557. */
  558. var forceReload = false,
  559. preparedRoute,
  560. preparedRouteIsUpdateOnly,
  561. $route = {
  562. routes: routes,
  563. /**
  564. * @ngdoc method
  565. * @name $route#reload
  566. *
  567. * @description
  568. * Causes `$route` service to reload the current route even if
  569. * {@link ng.$location $location} hasn't changed.
  570. *
  571. * As a result of that, {@link ngRoute.directive:ngView ngView}
  572. * creates new scope and reinstantiates the controller.
  573. */
  574. reload: function() {
  575. forceReload = true;
  576. var fakeLocationEvent = {
  577. defaultPrevented: false,
  578. preventDefault: function fakePreventDefault() {
  579. this.defaultPrevented = true;
  580. forceReload = false;
  581. }
  582. };
  583. $rootScope.$evalAsync(function() {
  584. prepareRoute(fakeLocationEvent);
  585. if (!fakeLocationEvent.defaultPrevented) commitRoute();
  586. });
  587. },
  588. /**
  589. * @ngdoc method
  590. * @name $route#updateParams
  591. *
  592. * @description
  593. * Causes `$route` service to update the current URL, replacing
  594. * current route parameters with those specified in `newParams`.
  595. * Provided property names that match the route's path segment
  596. * definitions will be interpolated into the location's path, while
  597. * remaining properties will be treated as query params.
  598. *
  599. * @param {!Object<string, string>} newParams mapping of URL parameter names to values
  600. */
  601. updateParams: function(newParams) {
  602. if (this.current && this.current.$$route) {
  603. newParams = angular.extend({}, this.current.params, newParams);
  604. $location.path(interpolate(this.current.$$route.originalPath, newParams));
  605. // interpolate modifies newParams, only query params are left
  606. $location.search(newParams);
  607. } else {
  608. throw $routeMinErr('norout', 'Tried updating route when with no current route');
  609. }
  610. }
  611. };
  612. $rootScope.$on('$locationChangeStart', prepareRoute);
  613. $rootScope.$on('$locationChangeSuccess', commitRoute);
  614. return $route;
  615. /////////////////////////////////////////////////////
  616. /**
  617. * @param on {string} current url
  618. * @param route {Object} route regexp to match the url against
  619. * @return {?Object}
  620. *
  621. * @description
  622. * Check if the route matches the current url.
  623. *
  624. * Inspired by match in
  625. * visionmedia/express/lib/router/router.js.
  626. */
  627. function switchRouteMatcher(on, route) {
  628. var keys = route.keys,
  629. params = {};
  630. if (!route.regexp) return null;
  631. var m = route.regexp.exec(on);
  632. if (!m) return null;
  633. for (var i = 1, len = m.length; i < len; ++i) {
  634. var key = keys[i - 1];
  635. var val = m[i];
  636. if (key && val) {
  637. params[key.name] = val;
  638. }
  639. }
  640. return params;
  641. }
  642. function prepareRoute($locationEvent) {
  643. var lastRoute = $route.current;
  644. preparedRoute = parseRoute();
  645. preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
  646. && angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
  647. && !preparedRoute.reloadOnSearch && !forceReload;
  648. if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
  649. if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
  650. if ($locationEvent) {
  651. $locationEvent.preventDefault();
  652. }
  653. }
  654. }
  655. }
  656. function commitRoute() {
  657. var lastRoute = $route.current;
  658. var nextRoute = preparedRoute;
  659. if (preparedRouteIsUpdateOnly) {
  660. lastRoute.params = nextRoute.params;
  661. angular.copy(lastRoute.params, $routeParams);
  662. $rootScope.$broadcast('$routeUpdate', lastRoute);
  663. } else if (nextRoute || lastRoute) {
  664. forceReload = false;
  665. $route.current = nextRoute;
  666. var nextRoutePromise = $q.resolve(nextRoute);
  667. $browser.$$incOutstandingRequestCount();
  668. nextRoutePromise.
  669. then(getRedirectionData).
  670. then(handlePossibleRedirection).
  671. then(function(keepProcessingRoute) {
  672. return keepProcessingRoute && nextRoutePromise.
  673. then(resolveLocals).
  674. then(function(locals) {
  675. // after route change
  676. if (nextRoute === $route.current) {
  677. if (nextRoute) {
  678. nextRoute.locals = locals;
  679. angular.copy(nextRoute.params, $routeParams);
  680. }
  681. $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
  682. }
  683. });
  684. }).catch(function(error) {
  685. if (nextRoute === $route.current) {
  686. $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
  687. }
  688. }).finally(function() {
  689. // Because `commitRoute()` is called from a `$rootScope.$evalAsync` block (see
  690. // `$locationWatch`), this `$$completeOutstandingRequest()` call will not cause
  691. // `outstandingRequestCount` to hit zero. This is important in case we are redirecting
  692. // to a new route which also requires some asynchronous work.
  693. $browser.$$completeOutstandingRequest(noop);
  694. });
  695. }
  696. }
  697. function getRedirectionData(route) {
  698. var data = {
  699. route: route,
  700. hasRedirection: false
  701. };
  702. if (route) {
  703. if (route.redirectTo) {
  704. if (angular.isString(route.redirectTo)) {
  705. data.path = interpolate(route.redirectTo, route.params);
  706. data.search = route.params;
  707. data.hasRedirection = true;
  708. } else {
  709. var oldPath = $location.path();
  710. var oldSearch = $location.search();
  711. var newUrl = route.redirectTo(route.pathParams, oldPath, oldSearch);
  712. if (angular.isDefined(newUrl)) {
  713. data.url = newUrl;
  714. data.hasRedirection = true;
  715. }
  716. }
  717. } else if (route.resolveRedirectTo) {
  718. return $q.
  719. resolve($injector.invoke(route.resolveRedirectTo)).
  720. then(function(newUrl) {
  721. if (angular.isDefined(newUrl)) {
  722. data.url = newUrl;
  723. data.hasRedirection = true;
  724. }
  725. return data;
  726. });
  727. }
  728. }
  729. return data;
  730. }
  731. function handlePossibleRedirection(data) {
  732. var keepProcessingRoute = true;
  733. if (data.route !== $route.current) {
  734. keepProcessingRoute = false;
  735. } else if (data.hasRedirection) {
  736. var oldUrl = $location.url();
  737. var newUrl = data.url;
  738. if (newUrl) {
  739. $location.
  740. url(newUrl).
  741. replace();
  742. } else {
  743. newUrl = $location.
  744. path(data.path).
  745. search(data.search).
  746. replace().
  747. url();
  748. }
  749. if (newUrl !== oldUrl) {
  750. // Exit out and don't process current next value,
  751. // wait for next location change from redirect
  752. keepProcessingRoute = false;
  753. }
  754. }
  755. return keepProcessingRoute;
  756. }
  757. function resolveLocals(route) {
  758. if (route) {
  759. var locals = angular.extend({}, route.resolve);
  760. angular.forEach(locals, function(value, key) {
  761. locals[key] = angular.isString(value) ?
  762. $injector.get(value) :
  763. $injector.invoke(value, null, null, key);
  764. });
  765. var template = getTemplateFor(route);
  766. if (angular.isDefined(template)) {
  767. locals['$template'] = template;
  768. }
  769. return $q.all(locals);
  770. }
  771. }
  772. function getTemplateFor(route) {
  773. var template, templateUrl;
  774. if (angular.isDefined(template = route.template)) {
  775. if (angular.isFunction(template)) {
  776. template = template(route.params);
  777. }
  778. } else if (angular.isDefined(templateUrl = route.templateUrl)) {
  779. if (angular.isFunction(templateUrl)) {
  780. templateUrl = templateUrl(route.params);
  781. }
  782. if (angular.isDefined(templateUrl)) {
  783. route.loadedTemplateUrl = $sce.valueOf(templateUrl);
  784. template = $templateRequest(templateUrl);
  785. }
  786. }
  787. return template;
  788. }
  789. /**
  790. * @returns {Object} the current active route, by matching it against the URL
  791. */
  792. function parseRoute() {
  793. // Match a route
  794. var params, match;
  795. angular.forEach(routes, function(route, path) {
  796. if (!match && (params = switchRouteMatcher($location.path(), route))) {
  797. match = inherit(route, {
  798. params: angular.extend({}, $location.search(), params),
  799. pathParams: params});
  800. match.$$route = route;
  801. }
  802. });
  803. // No route matched; fallback to "otherwise" route
  804. return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
  805. }
  806. /**
  807. * @returns {string} interpolation of the redirect path with the parameters
  808. */
  809. function interpolate(string, params) {
  810. var result = [];
  811. angular.forEach((string || '').split(':'), function(segment, i) {
  812. if (i === 0) {
  813. result.push(segment);
  814. } else {
  815. var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
  816. var key = segmentMatch[1];
  817. result.push(params[key]);
  818. result.push(segmentMatch[2] || '');
  819. delete params[key];
  820. }
  821. });
  822. return result.join('');
  823. }
  824. }];
  825. }
  826. instantiateRoute.$inject = ['$injector'];
  827. function instantiateRoute($injector) {
  828. if (isEagerInstantiationEnabled) {
  829. // Instantiate `$route`
  830. $injector.get('$route');
  831. }
  832. }
  833. ngRouteModule.provider('$routeParams', $RouteParamsProvider);
  834. /**
  835. * @ngdoc service
  836. * @name $routeParams
  837. * @requires $route
  838. * @this
  839. *
  840. * @description
  841. * The `$routeParams` service allows you to retrieve the current set of route parameters.
  842. *
  843. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  844. *
  845. * The route parameters are a combination of {@link ng.$location `$location`}'s
  846. * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
  847. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
  848. *
  849. * In case of parameter name collision, `path` params take precedence over `search` params.
  850. *
  851. * The service guarantees that the identity of the `$routeParams` object will remain unchanged
  852. * (but its properties will likely change) even when a route change occurs.
  853. *
  854. * Note that the `$routeParams` are only updated *after* a route change completes successfully.
  855. * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
  856. * Instead you can use `$route.current.params` to access the new route's parameters.
  857. *
  858. * @example
  859. * ```js
  860. * // Given:
  861. * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
  862. * // Route: /Chapter/:chapterId/Section/:sectionId
  863. * //
  864. * // Then
  865. * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
  866. * ```
  867. */
  868. function $RouteParamsProvider() {
  869. this.$get = function() { return {}; };
  870. }
  871. ngRouteModule.directive('ngView', ngViewFactory);
  872. ngRouteModule.directive('ngView', ngViewFillContentFactory);
  873. /**
  874. * @ngdoc directive
  875. * @name ngView
  876. * @restrict ECA
  877. *
  878. * @description
  879. * # Overview
  880. * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
  881. * including the rendered template of the current route into the main layout (`index.html`) file.
  882. * Every time the current route changes, the included view changes with it according to the
  883. * configuration of the `$route` service.
  884. *
  885. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  886. *
  887. * @animations
  888. * | Animation | Occurs |
  889. * |----------------------------------|-------------------------------------|
  890. * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
  891. * | {@link ng.$animate#leave leave} | when the old element is removed from to the DOM |
  892. *
  893. * The enter and leave animation occur concurrently.
  894. *
  895. * @scope
  896. * @priority 400
  897. * @param {string=} onload Expression to evaluate whenever the view updates.
  898. *
  899. * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
  900. * $anchorScroll} to scroll the viewport after the view is updated.
  901. *
  902. * - If the attribute is not set, disable scrolling.
  903. * - If the attribute is set without value, enable scrolling.
  904. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
  905. * as an expression yields a truthy value.
  906. * @example
  907. <example name="ngView-directive" module="ngViewExample"
  908. deps="angular-route.js;angular-animate.js"
  909. animations="true" fixBase="true">
  910. <file name="index.html">
  911. <div ng-controller="MainCtrl as main">
  912. Choose:
  913. <a href="Book/Moby">Moby</a> |
  914. <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  915. <a href="Book/Gatsby">Gatsby</a> |
  916. <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  917. <a href="Book/Scarlet">Scarlet Letter</a><br/>
  918. <div class="view-animate-container">
  919. <div ng-view class="view-animate"></div>
  920. </div>
  921. <hr />
  922. <pre>$location.path() = {{main.$location.path()}}</pre>
  923. <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
  924. <pre>$route.current.params = {{main.$route.current.params}}</pre>
  925. <pre>$routeParams = {{main.$routeParams}}</pre>
  926. </div>
  927. </file>
  928. <file name="book.html">
  929. <div>
  930. controller: {{book.name}}<br />
  931. Book Id: {{book.params.bookId}}<br />
  932. </div>
  933. </file>
  934. <file name="chapter.html">
  935. <div>
  936. controller: {{chapter.name}}<br />
  937. Book Id: {{chapter.params.bookId}}<br />
  938. Chapter Id: {{chapter.params.chapterId}}
  939. </div>
  940. </file>
  941. <file name="animations.css">
  942. .view-animate-container {
  943. position:relative;
  944. height:100px!important;
  945. background:white;
  946. border:1px solid black;
  947. height:40px;
  948. overflow:hidden;
  949. }
  950. .view-animate {
  951. padding:10px;
  952. }
  953. .view-animate.ng-enter, .view-animate.ng-leave {
  954. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  955. display:block;
  956. width:100%;
  957. border-left:1px solid black;
  958. position:absolute;
  959. top:0;
  960. left:0;
  961. right:0;
  962. bottom:0;
  963. padding:10px;
  964. }
  965. .view-animate.ng-enter {
  966. left:100%;
  967. }
  968. .view-animate.ng-enter.ng-enter-active {
  969. left:0;
  970. }
  971. .view-animate.ng-leave.ng-leave-active {
  972. left:-100%;
  973. }
  974. </file>
  975. <file name="script.js">
  976. angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
  977. .config(['$routeProvider', '$locationProvider',
  978. function($routeProvider, $locationProvider) {
  979. $routeProvider
  980. .when('/Book/:bookId', {
  981. templateUrl: 'book.html',
  982. controller: 'BookCtrl',
  983. controllerAs: 'book'
  984. })
  985. .when('/Book/:bookId/ch/:chapterId', {
  986. templateUrl: 'chapter.html',
  987. controller: 'ChapterCtrl',
  988. controllerAs: 'chapter'
  989. });
  990. $locationProvider.html5Mode(true);
  991. }])
  992. .controller('MainCtrl', ['$route', '$routeParams', '$location',
  993. function MainCtrl($route, $routeParams, $location) {
  994. this.$route = $route;
  995. this.$location = $location;
  996. this.$routeParams = $routeParams;
  997. }])
  998. .controller('BookCtrl', ['$routeParams', function BookCtrl($routeParams) {
  999. this.name = 'BookCtrl';
  1000. this.params = $routeParams;
  1001. }])
  1002. .controller('ChapterCtrl', ['$routeParams', function ChapterCtrl($routeParams) {
  1003. this.name = 'ChapterCtrl';
  1004. this.params = $routeParams;
  1005. }]);
  1006. </file>
  1007. <file name="protractor.js" type="protractor">
  1008. it('should load and compile correct template', function() {
  1009. element(by.linkText('Moby: Ch1')).click();
  1010. var content = element(by.css('[ng-view]')).getText();
  1011. expect(content).toMatch(/controller: ChapterCtrl/);
  1012. expect(content).toMatch(/Book Id: Moby/);
  1013. expect(content).toMatch(/Chapter Id: 1/);
  1014. element(by.partialLinkText('Scarlet')).click();
  1015. content = element(by.css('[ng-view]')).getText();
  1016. expect(content).toMatch(/controller: BookCtrl/);
  1017. expect(content).toMatch(/Book Id: Scarlet/);
  1018. });
  1019. </file>
  1020. </example>
  1021. */
  1022. /**
  1023. * @ngdoc event
  1024. * @name ngView#$viewContentLoaded
  1025. * @eventType emit on the current ngView scope
  1026. * @description
  1027. * Emitted every time the ngView content is reloaded.
  1028. */
  1029. ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
  1030. function ngViewFactory($route, $anchorScroll, $animate) {
  1031. return {
  1032. restrict: 'ECA',
  1033. terminal: true,
  1034. priority: 400,
  1035. transclude: 'element',
  1036. link: function(scope, $element, attr, ctrl, $transclude) {
  1037. var currentScope,
  1038. currentElement,
  1039. previousLeaveAnimation,
  1040. autoScrollExp = attr.autoscroll,
  1041. onloadExp = attr.onload || '';
  1042. scope.$on('$routeChangeSuccess', update);
  1043. update();
  1044. function cleanupLastView() {
  1045. if (previousLeaveAnimation) {
  1046. $animate.cancel(previousLeaveAnimation);
  1047. previousLeaveAnimation = null;
  1048. }
  1049. if (currentScope) {
  1050. currentScope.$destroy();
  1051. currentScope = null;
  1052. }
  1053. if (currentElement) {
  1054. previousLeaveAnimation = $animate.leave(currentElement);
  1055. previousLeaveAnimation.done(function(response) {
  1056. if (response !== false) previousLeaveAnimation = null;
  1057. });
  1058. currentElement = null;
  1059. }
  1060. }
  1061. function update() {
  1062. var locals = $route.current && $route.current.locals,
  1063. template = locals && locals.$template;
  1064. if (angular.isDefined(template)) {
  1065. var newScope = scope.$new();
  1066. var current = $route.current;
  1067. // Note: This will also link all children of ng-view that were contained in the original
  1068. // html. If that content contains controllers, ... they could pollute/change the scope.
  1069. // However, using ng-view on an element with additional content does not make sense...
  1070. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  1071. // function is called before linking the content, which would apply child
  1072. // directives to non existing elements.
  1073. var clone = $transclude(newScope, function(clone) {
  1074. $animate.enter(clone, null, currentElement || $element).done(function onNgViewEnter(response) {
  1075. if (response !== false && angular.isDefined(autoScrollExp)
  1076. && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  1077. $anchorScroll();
  1078. }
  1079. });
  1080. cleanupLastView();
  1081. });
  1082. currentElement = clone;
  1083. currentScope = current.scope = newScope;
  1084. currentScope.$emit('$viewContentLoaded');
  1085. currentScope.$eval(onloadExp);
  1086. } else {
  1087. cleanupLastView();
  1088. }
  1089. }
  1090. }
  1091. };
  1092. }
  1093. // This directive is called during the $transclude call of the first `ngView` directive.
  1094. // It will replace and compile the content of the element with the loaded template.
  1095. // We need this directive so that the element content is already filled when
  1096. // the link function of another directive on the same element as ngView
  1097. // is called.
  1098. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
  1099. function ngViewFillContentFactory($compile, $controller, $route) {
  1100. return {
  1101. restrict: 'ECA',
  1102. priority: -400,
  1103. link: function(scope, $element) {
  1104. var current = $route.current,
  1105. locals = current.locals;
  1106. $element.html(locals.$template);
  1107. var link = $compile($element.contents());
  1108. if (current.controller) {
  1109. locals.$scope = scope;
  1110. var controller = $controller(current.controller, locals);
  1111. if (current.controllerAs) {
  1112. scope[current.controllerAs] = controller;
  1113. }
  1114. $element.data('$ngControllerController', controller);
  1115. $element.children().data('$ngControllerController', controller);
  1116. }
  1117. scope[current.resolveAs || '$resolve'] = locals;
  1118. link(scope);
  1119. }
  1120. };
  1121. }
  1122. })(window, window.angular);