You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1216 lines
43 KiB

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