angular-route.js 43 KB

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