angular-route.js 44 KB

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