angular-route.js 35 KB

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