angular-route.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. /**
  2. * @license AngularJS v1.4.1
  3. * (c) 2010-2015 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=}` – An identifier name for a reference to the controller.
  78. * If present, the controller will be 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. * The `reloadOnSearch` property has been set to false, and we are reusing the same
  425. * instance of the Controller.
  426. *
  427. * @param {Object} angularEvent Synthetic event object
  428. * @param {Route} current Current/previous route information.
  429. */
  430. var forceReload = false,
  431. preparedRoute,
  432. preparedRouteIsUpdateOnly,
  433. $route = {
  434. routes: routes,
  435. /**
  436. * @ngdoc method
  437. * @name $route#reload
  438. *
  439. * @description
  440. * Causes `$route` service to reload the current route even if
  441. * {@link ng.$location $location} hasn't changed.
  442. *
  443. * As a result of that, {@link ngRoute.directive:ngView ngView}
  444. * creates new scope and reinstantiates the controller.
  445. */
  446. reload: function() {
  447. forceReload = true;
  448. $rootScope.$evalAsync(function() {
  449. // Don't support cancellation of a reload for now...
  450. prepareRoute();
  451. commitRoute();
  452. });
  453. },
  454. /**
  455. * @ngdoc method
  456. * @name $route#updateParams
  457. *
  458. * @description
  459. * Causes `$route` service to update the current URL, replacing
  460. * current route parameters with those specified in `newParams`.
  461. * Provided property names that match the route's path segment
  462. * definitions will be interpolated into the location's path, while
  463. * remaining properties will be treated as query params.
  464. *
  465. * @param {!Object<string, string>} newParams mapping of URL parameter names to values
  466. */
  467. updateParams: function(newParams) {
  468. if (this.current && this.current.$$route) {
  469. newParams = angular.extend({}, this.current.params, newParams);
  470. $location.path(interpolate(this.current.$$route.originalPath, newParams));
  471. // interpolate modifies newParams, only query params are left
  472. $location.search(newParams);
  473. } else {
  474. throw $routeMinErr('norout', 'Tried updating route when with no current route');
  475. }
  476. }
  477. };
  478. $rootScope.$on('$locationChangeStart', prepareRoute);
  479. $rootScope.$on('$locationChangeSuccess', commitRoute);
  480. return $route;
  481. /////////////////////////////////////////////////////
  482. /**
  483. * @param on {string} current url
  484. * @param route {Object} route regexp to match the url against
  485. * @return {?Object}
  486. *
  487. * @description
  488. * Check if the route matches the current url.
  489. *
  490. * Inspired by match in
  491. * visionmedia/express/lib/router/router.js.
  492. */
  493. function switchRouteMatcher(on, route) {
  494. var keys = route.keys,
  495. params = {};
  496. if (!route.regexp) return null;
  497. var m = route.regexp.exec(on);
  498. if (!m) return null;
  499. for (var i = 1, len = m.length; i < len; ++i) {
  500. var key = keys[i - 1];
  501. var val = m[i];
  502. if (key && val) {
  503. params[key.name] = val;
  504. }
  505. }
  506. return params;
  507. }
  508. function prepareRoute($locationEvent) {
  509. var lastRoute = $route.current;
  510. preparedRoute = parseRoute();
  511. preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
  512. && angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
  513. && !preparedRoute.reloadOnSearch && !forceReload;
  514. if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
  515. if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
  516. if ($locationEvent) {
  517. $locationEvent.preventDefault();
  518. }
  519. }
  520. }
  521. }
  522. function commitRoute() {
  523. var lastRoute = $route.current;
  524. var nextRoute = preparedRoute;
  525. if (preparedRouteIsUpdateOnly) {
  526. lastRoute.params = nextRoute.params;
  527. angular.copy(lastRoute.params, $routeParams);
  528. $rootScope.$broadcast('$routeUpdate', lastRoute);
  529. } else if (nextRoute || lastRoute) {
  530. forceReload = false;
  531. $route.current = nextRoute;
  532. if (nextRoute) {
  533. if (nextRoute.redirectTo) {
  534. if (angular.isString(nextRoute.redirectTo)) {
  535. $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
  536. .replace();
  537. } else {
  538. $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
  539. .replace();
  540. }
  541. }
  542. }
  543. $q.when(nextRoute).
  544. then(function() {
  545. if (nextRoute) {
  546. var locals = angular.extend({}, nextRoute.resolve),
  547. template, templateUrl;
  548. angular.forEach(locals, function(value, key) {
  549. locals[key] = angular.isString(value) ?
  550. $injector.get(value) : $injector.invoke(value, null, null, key);
  551. });
  552. if (angular.isDefined(template = nextRoute.template)) {
  553. if (angular.isFunction(template)) {
  554. template = template(nextRoute.params);
  555. }
  556. } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) {
  557. if (angular.isFunction(templateUrl)) {
  558. templateUrl = templateUrl(nextRoute.params);
  559. }
  560. templateUrl = $sce.getTrustedResourceUrl(templateUrl);
  561. if (angular.isDefined(templateUrl)) {
  562. nextRoute.loadedTemplateUrl = templateUrl;
  563. template = $templateRequest(templateUrl);
  564. }
  565. }
  566. if (angular.isDefined(template)) {
  567. locals['$template'] = template;
  568. }
  569. return $q.all(locals);
  570. }
  571. }).
  572. then(function(locals) {
  573. // after route change
  574. if (nextRoute == $route.current) {
  575. if (nextRoute) {
  576. nextRoute.locals = locals;
  577. angular.copy(nextRoute.params, $routeParams);
  578. }
  579. $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
  580. }
  581. }, function(error) {
  582. if (nextRoute == $route.current) {
  583. $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
  584. }
  585. });
  586. }
  587. }
  588. /**
  589. * @returns {Object} the current active route, by matching it against the URL
  590. */
  591. function parseRoute() {
  592. // Match a route
  593. var params, match;
  594. angular.forEach(routes, function(route, path) {
  595. if (!match && (params = switchRouteMatcher($location.path(), route))) {
  596. match = inherit(route, {
  597. params: angular.extend({}, $location.search(), params),
  598. pathParams: params});
  599. match.$$route = route;
  600. }
  601. });
  602. // No route matched; fallback to "otherwise" route
  603. return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
  604. }
  605. /**
  606. * @returns {string} interpolation of the redirect path with the parameters
  607. */
  608. function interpolate(string, params) {
  609. var result = [];
  610. angular.forEach((string || '').split(':'), function(segment, i) {
  611. if (i === 0) {
  612. result.push(segment);
  613. } else {
  614. var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
  615. var key = segmentMatch[1];
  616. result.push(params[key]);
  617. result.push(segmentMatch[2] || '');
  618. delete params[key];
  619. }
  620. });
  621. return result.join('');
  622. }
  623. }];
  624. }
  625. ngRouteModule.provider('$routeParams', $RouteParamsProvider);
  626. /**
  627. * @ngdoc service
  628. * @name $routeParams
  629. * @requires $route
  630. *
  631. * @description
  632. * The `$routeParams` service allows you to retrieve the current set of route parameters.
  633. *
  634. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  635. *
  636. * The route parameters are a combination of {@link ng.$location `$location`}'s
  637. * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
  638. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
  639. *
  640. * In case of parameter name collision, `path` params take precedence over `search` params.
  641. *
  642. * The service guarantees that the identity of the `$routeParams` object will remain unchanged
  643. * (but its properties will likely change) even when a route change occurs.
  644. *
  645. * Note that the `$routeParams` are only updated *after* a route change completes successfully.
  646. * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
  647. * Instead you can use `$route.current.params` to access the new route's parameters.
  648. *
  649. * @example
  650. * ```js
  651. * // Given:
  652. * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
  653. * // Route: /Chapter/:chapterId/Section/:sectionId
  654. * //
  655. * // Then
  656. * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
  657. * ```
  658. */
  659. function $RouteParamsProvider() {
  660. this.$get = function() { return {}; };
  661. }
  662. ngRouteModule.directive('ngView', ngViewFactory);
  663. ngRouteModule.directive('ngView', ngViewFillContentFactory);
  664. /**
  665. * @ngdoc directive
  666. * @name ngView
  667. * @restrict ECA
  668. *
  669. * @description
  670. * # Overview
  671. * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
  672. * including the rendered template of the current route into the main layout (`index.html`) file.
  673. * Every time the current route changes, the included view changes with it according to the
  674. * configuration of the `$route` service.
  675. *
  676. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  677. *
  678. * @animations
  679. * enter - animation is used to bring new content into the browser.
  680. * leave - animation is used to animate existing content away.
  681. *
  682. * The enter and leave animation occur concurrently.
  683. *
  684. * @scope
  685. * @priority 400
  686. * @param {string=} onload Expression to evaluate whenever the view updates.
  687. *
  688. * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
  689. * $anchorScroll} to scroll the viewport after the view is updated.
  690. *
  691. * - If the attribute is not set, disable scrolling.
  692. * - If the attribute is set without value, enable scrolling.
  693. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
  694. * as an expression yields a truthy value.
  695. * @example
  696. <example name="ngView-directive" module="ngViewExample"
  697. deps="angular-route.js;angular-animate.js"
  698. animations="true" fixBase="true">
  699. <file name="index.html">
  700. <div ng-controller="MainCtrl as main">
  701. Choose:
  702. <a href="Book/Moby">Moby</a> |
  703. <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  704. <a href="Book/Gatsby">Gatsby</a> |
  705. <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  706. <a href="Book/Scarlet">Scarlet Letter</a><br/>
  707. <div class="view-animate-container">
  708. <div ng-view class="view-animate"></div>
  709. </div>
  710. <hr />
  711. <pre>$location.path() = {{main.$location.path()}}</pre>
  712. <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
  713. <pre>$route.current.params = {{main.$route.current.params}}</pre>
  714. <pre>$routeParams = {{main.$routeParams}}</pre>
  715. </div>
  716. </file>
  717. <file name="book.html">
  718. <div>
  719. controller: {{book.name}}<br />
  720. Book Id: {{book.params.bookId}}<br />
  721. </div>
  722. </file>
  723. <file name="chapter.html">
  724. <div>
  725. controller: {{chapter.name}}<br />
  726. Book Id: {{chapter.params.bookId}}<br />
  727. Chapter Id: {{chapter.params.chapterId}}
  728. </div>
  729. </file>
  730. <file name="animations.css">
  731. .view-animate-container {
  732. position:relative;
  733. height:100px!important;
  734. background:white;
  735. border:1px solid black;
  736. height:40px;
  737. overflow:hidden;
  738. }
  739. .view-animate {
  740. padding:10px;
  741. }
  742. .view-animate.ng-enter, .view-animate.ng-leave {
  743. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  744. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  745. display:block;
  746. width:100%;
  747. border-left:1px solid black;
  748. position:absolute;
  749. top:0;
  750. left:0;
  751. right:0;
  752. bottom:0;
  753. padding:10px;
  754. }
  755. .view-animate.ng-enter {
  756. left:100%;
  757. }
  758. .view-animate.ng-enter.ng-enter-active {
  759. left:0;
  760. }
  761. .view-animate.ng-leave.ng-leave-active {
  762. left:-100%;
  763. }
  764. </file>
  765. <file name="script.js">
  766. angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
  767. .config(['$routeProvider', '$locationProvider',
  768. function($routeProvider, $locationProvider) {
  769. $routeProvider
  770. .when('/Book/:bookId', {
  771. templateUrl: 'book.html',
  772. controller: 'BookCtrl',
  773. controllerAs: 'book'
  774. })
  775. .when('/Book/:bookId/ch/:chapterId', {
  776. templateUrl: 'chapter.html',
  777. controller: 'ChapterCtrl',
  778. controllerAs: 'chapter'
  779. });
  780. $locationProvider.html5Mode(true);
  781. }])
  782. .controller('MainCtrl', ['$route', '$routeParams', '$location',
  783. function($route, $routeParams, $location) {
  784. this.$route = $route;
  785. this.$location = $location;
  786. this.$routeParams = $routeParams;
  787. }])
  788. .controller('BookCtrl', ['$routeParams', function($routeParams) {
  789. this.name = "BookCtrl";
  790. this.params = $routeParams;
  791. }])
  792. .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
  793. this.name = "ChapterCtrl";
  794. this.params = $routeParams;
  795. }]);
  796. </file>
  797. <file name="protractor.js" type="protractor">
  798. it('should load and compile correct template', function() {
  799. element(by.linkText('Moby: Ch1')).click();
  800. var content = element(by.css('[ng-view]')).getText();
  801. expect(content).toMatch(/controller\: ChapterCtrl/);
  802. expect(content).toMatch(/Book Id\: Moby/);
  803. expect(content).toMatch(/Chapter Id\: 1/);
  804. element(by.partialLinkText('Scarlet')).click();
  805. content = element(by.css('[ng-view]')).getText();
  806. expect(content).toMatch(/controller\: BookCtrl/);
  807. expect(content).toMatch(/Book Id\: Scarlet/);
  808. });
  809. </file>
  810. </example>
  811. */
  812. /**
  813. * @ngdoc event
  814. * @name ngView#$viewContentLoaded
  815. * @eventType emit on the current ngView scope
  816. * @description
  817. * Emitted every time the ngView content is reloaded.
  818. */
  819. ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
  820. function ngViewFactory($route, $anchorScroll, $animate) {
  821. return {
  822. restrict: 'ECA',
  823. terminal: true,
  824. priority: 400,
  825. transclude: 'element',
  826. link: function(scope, $element, attr, ctrl, $transclude) {
  827. var currentScope,
  828. currentElement,
  829. previousLeaveAnimation,
  830. autoScrollExp = attr.autoscroll,
  831. onloadExp = attr.onload || '';
  832. scope.$on('$routeChangeSuccess', update);
  833. update();
  834. function cleanupLastView() {
  835. if (previousLeaveAnimation) {
  836. $animate.cancel(previousLeaveAnimation);
  837. previousLeaveAnimation = null;
  838. }
  839. if (currentScope) {
  840. currentScope.$destroy();
  841. currentScope = null;
  842. }
  843. if (currentElement) {
  844. previousLeaveAnimation = $animate.leave(currentElement);
  845. previousLeaveAnimation.then(function() {
  846. previousLeaveAnimation = null;
  847. });
  848. currentElement = null;
  849. }
  850. }
  851. function update() {
  852. var locals = $route.current && $route.current.locals,
  853. template = locals && locals.$template;
  854. if (angular.isDefined(template)) {
  855. var newScope = scope.$new();
  856. var current = $route.current;
  857. // Note: This will also link all children of ng-view that were contained in the original
  858. // html. If that content contains controllers, ... they could pollute/change the scope.
  859. // However, using ng-view on an element with additional content does not make sense...
  860. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  861. // function is called before linking the content, which would apply child
  862. // directives to non existing elements.
  863. var clone = $transclude(newScope, function(clone) {
  864. $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
  865. if (angular.isDefined(autoScrollExp)
  866. && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  867. $anchorScroll();
  868. }
  869. });
  870. cleanupLastView();
  871. });
  872. currentElement = clone;
  873. currentScope = current.scope = newScope;
  874. currentScope.$emit('$viewContentLoaded');
  875. currentScope.$eval(onloadExp);
  876. } else {
  877. cleanupLastView();
  878. }
  879. }
  880. }
  881. };
  882. }
  883. // This directive is called during the $transclude call of the first `ngView` directive.
  884. // It will replace and compile the content of the element with the loaded template.
  885. // We need this directive so that the element content is already filled when
  886. // the link function of another directive on the same element as ngView
  887. // is called.
  888. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
  889. function ngViewFillContentFactory($compile, $controller, $route) {
  890. return {
  891. restrict: 'ECA',
  892. priority: -400,
  893. link: function(scope, $element) {
  894. var current = $route.current,
  895. locals = current.locals;
  896. $element.html(locals.$template);
  897. var link = $compile($element.contents());
  898. if (current.controller) {
  899. locals.$scope = scope;
  900. var controller = $controller(current.controller, locals);
  901. if (current.controllerAs) {
  902. scope[current.controllerAs] = controller;
  903. }
  904. $element.data('$ngControllerController', controller);
  905. $element.children().data('$ngControllerController', controller);
  906. }
  907. link(scope);
  908. }
  909. };
  910. }
  911. })(window, window.angular);