angular-route.js 35 KB

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