angular-route.js 44 KB

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