angular-route.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. /**
  2. * @license AngularJS v1.5.0-rc.0
  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 change has happened successfully.
  399. * The `resolve` dependencies are now available in the `current.locals` property.
  400. *
  401. * {@link ngRoute.directive:ngView ngView} listens for the directive
  402. * to instantiate the controller and render the view.
  403. *
  404. * @param {Object} angularEvent Synthetic event object.
  405. * @param {Route} current Current route information.
  406. * @param {Route|Undefined} previous Previous route information, or undefined if current is
  407. * first route entered.
  408. */
  409. /**
  410. * @ngdoc event
  411. * @name $route#$routeChangeError
  412. * @eventType broadcast on root scope
  413. * @description
  414. * Broadcasted if any of the resolve promises are rejected.
  415. *
  416. * @param {Object} angularEvent Synthetic event object
  417. * @param {Route} current Current route information.
  418. * @param {Route} previous Previous route information.
  419. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
  420. */
  421. /**
  422. * @ngdoc event
  423. * @name $route#$routeUpdate
  424. * @eventType broadcast on root scope
  425. * @description
  426. * The `reloadOnSearch` property has been set to false, and we are reusing the same
  427. * instance of the Controller.
  428. *
  429. * @param {Object} angularEvent Synthetic event object
  430. * @param {Route} current Current/previous route information.
  431. */
  432. var forceReload = false,
  433. preparedRoute,
  434. preparedRouteIsUpdateOnly,
  435. $route = {
  436. routes: routes,
  437. /**
  438. * @ngdoc method
  439. * @name $route#reload
  440. *
  441. * @description
  442. * Causes `$route` service to reload the current route even if
  443. * {@link ng.$location $location} hasn't changed.
  444. *
  445. * As a result of that, {@link ngRoute.directive:ngView ngView}
  446. * creates new scope and reinstantiates the controller.
  447. */
  448. reload: function() {
  449. forceReload = true;
  450. $rootScope.$evalAsync(function() {
  451. // Don't support cancellation of a reload for now...
  452. prepareRoute();
  453. commitRoute();
  454. });
  455. },
  456. /**
  457. * @ngdoc method
  458. * @name $route#updateParams
  459. *
  460. * @description
  461. * Causes `$route` service to update the current URL, replacing
  462. * current route parameters with those specified in `newParams`.
  463. * Provided property names that match the route's path segment
  464. * definitions will be interpolated into the location's path, while
  465. * remaining properties will be treated as query params.
  466. *
  467. * @param {!Object<string, string>} newParams mapping of URL parameter names to values
  468. */
  469. updateParams: function(newParams) {
  470. if (this.current && this.current.$$route) {
  471. newParams = angular.extend({}, this.current.params, newParams);
  472. $location.path(interpolate(this.current.$$route.originalPath, newParams));
  473. // interpolate modifies newParams, only query params are left
  474. $location.search(newParams);
  475. } else {
  476. throw $routeMinErr('norout', 'Tried updating route when with no current route');
  477. }
  478. }
  479. };
  480. $rootScope.$on('$locationChangeStart', prepareRoute);
  481. $rootScope.$on('$locationChangeSuccess', commitRoute);
  482. return $route;
  483. /////////////////////////////////////////////////////
  484. /**
  485. * @param on {string} current url
  486. * @param route {Object} route regexp to match the url against
  487. * @return {?Object}
  488. *
  489. * @description
  490. * Check if the route matches the current url.
  491. *
  492. * Inspired by match in
  493. * visionmedia/express/lib/router/router.js.
  494. */
  495. function switchRouteMatcher(on, route) {
  496. var keys = route.keys,
  497. params = {};
  498. if (!route.regexp) return null;
  499. var m = route.regexp.exec(on);
  500. if (!m) return null;
  501. for (var i = 1, len = m.length; i < len; ++i) {
  502. var key = keys[i - 1];
  503. var val = m[i];
  504. if (key && val) {
  505. params[key.name] = val;
  506. }
  507. }
  508. return params;
  509. }
  510. function prepareRoute($locationEvent) {
  511. var lastRoute = $route.current;
  512. preparedRoute = parseRoute();
  513. preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
  514. && angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
  515. && !preparedRoute.reloadOnSearch && !forceReload;
  516. if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
  517. if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
  518. if ($locationEvent) {
  519. $locationEvent.preventDefault();
  520. }
  521. }
  522. }
  523. }
  524. function commitRoute() {
  525. var lastRoute = $route.current;
  526. var nextRoute = preparedRoute;
  527. if (preparedRouteIsUpdateOnly) {
  528. lastRoute.params = nextRoute.params;
  529. angular.copy(lastRoute.params, $routeParams);
  530. $rootScope.$broadcast('$routeUpdate', lastRoute);
  531. } else if (nextRoute || lastRoute) {
  532. forceReload = false;
  533. $route.current = nextRoute;
  534. if (nextRoute) {
  535. if (nextRoute.redirectTo) {
  536. if (angular.isString(nextRoute.redirectTo)) {
  537. $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
  538. .replace();
  539. } else {
  540. $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
  541. .replace();
  542. }
  543. }
  544. }
  545. $q.when(nextRoute).
  546. then(function() {
  547. if (nextRoute) {
  548. var locals = angular.extend({}, nextRoute.resolve),
  549. template, templateUrl;
  550. angular.forEach(locals, function(value, key) {
  551. locals[key] = angular.isString(value) ?
  552. $injector.get(value) : $injector.invoke(value, null, null, key);
  553. });
  554. if (angular.isDefined(template = nextRoute.template)) {
  555. if (angular.isFunction(template)) {
  556. template = template(nextRoute.params);
  557. }
  558. } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) {
  559. if (angular.isFunction(templateUrl)) {
  560. templateUrl = templateUrl(nextRoute.params);
  561. }
  562. if (angular.isDefined(templateUrl)) {
  563. nextRoute.loadedTemplateUrl = $sce.valueOf(templateUrl);
  564. template = $templateRequest(templateUrl);
  565. }
  566. }
  567. if (angular.isDefined(template)) {
  568. locals['$template'] = template;
  569. }
  570. return $q.all(locals);
  571. }
  572. }).
  573. then(function(locals) {
  574. // after route change
  575. if (nextRoute == $route.current) {
  576. if (nextRoute) {
  577. nextRoute.locals = locals;
  578. angular.copy(nextRoute.params, $routeParams);
  579. }
  580. $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
  581. }
  582. }, function(error) {
  583. if (nextRoute == $route.current) {
  584. $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
  585. }
  586. });
  587. }
  588. }
  589. /**
  590. * @returns {Object} the current active route, by matching it against the URL
  591. */
  592. function parseRoute() {
  593. // Match a route
  594. var params, match;
  595. angular.forEach(routes, function(route, path) {
  596. if (!match && (params = switchRouteMatcher($location.path(), route))) {
  597. match = inherit(route, {
  598. params: angular.extend({}, $location.search(), params),
  599. pathParams: params});
  600. match.$$route = route;
  601. }
  602. });
  603. // No route matched; fallback to "otherwise" route
  604. return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
  605. }
  606. /**
  607. * @returns {string} interpolation of the redirect path with the parameters
  608. */
  609. function interpolate(string, params) {
  610. var result = [];
  611. angular.forEach((string || '').split(':'), function(segment, i) {
  612. if (i === 0) {
  613. result.push(segment);
  614. } else {
  615. var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
  616. var key = segmentMatch[1];
  617. result.push(params[key]);
  618. result.push(segmentMatch[2] || '');
  619. delete params[key];
  620. }
  621. });
  622. return result.join('');
  623. }
  624. }];
  625. }
  626. ngRouteModule.provider('$routeParams', $RouteParamsProvider);
  627. /**
  628. * @ngdoc service
  629. * @name $routeParams
  630. * @requires $route
  631. *
  632. * @description
  633. * The `$routeParams` service allows you to retrieve the current set of route parameters.
  634. *
  635. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  636. *
  637. * The route parameters are a combination of {@link ng.$location `$location`}'s
  638. * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
  639. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
  640. *
  641. * In case of parameter name collision, `path` params take precedence over `search` params.
  642. *
  643. * The service guarantees that the identity of the `$routeParams` object will remain unchanged
  644. * (but its properties will likely change) even when a route change occurs.
  645. *
  646. * Note that the `$routeParams` are only updated *after* a route change completes successfully.
  647. * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
  648. * Instead you can use `$route.current.params` to access the new route's parameters.
  649. *
  650. * @example
  651. * ```js
  652. * // Given:
  653. * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
  654. * // Route: /Chapter/:chapterId/Section/:sectionId
  655. * //
  656. * // Then
  657. * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
  658. * ```
  659. */
  660. function $RouteParamsProvider() {
  661. this.$get = function() { return {}; };
  662. }
  663. ngRouteModule.directive('ngView', ngViewFactory);
  664. ngRouteModule.directive('ngView', ngViewFillContentFactory);
  665. /**
  666. * @ngdoc directive
  667. * @name ngView
  668. * @restrict ECA
  669. *
  670. * @description
  671. * # Overview
  672. * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
  673. * including the rendered template of the current route into the main layout (`index.html`) file.
  674. * Every time the current route changes, the included view changes with it according to the
  675. * configuration of the `$route` service.
  676. *
  677. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  678. *
  679. * @animations
  680. * enter - animation is used to bring new content into the browser.
  681. * leave - animation is used to animate existing content away.
  682. *
  683. * The enter and leave animation occur concurrently.
  684. *
  685. * @scope
  686. * @priority 400
  687. * @param {string=} onload Expression to evaluate whenever the view updates.
  688. *
  689. * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
  690. * $anchorScroll} to scroll the viewport after the view is updated.
  691. *
  692. * - If the attribute is not set, disable scrolling.
  693. * - If the attribute is set without value, enable scrolling.
  694. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
  695. * as an expression yields a truthy value.
  696. * @example
  697. <example name="ngView-directive" module="ngViewExample"
  698. deps="angular-route.js;angular-animate.js"
  699. animations="true" fixBase="true">
  700. <file name="index.html">
  701. <div ng-controller="MainCtrl as main">
  702. Choose:
  703. <a href="Book/Moby">Moby</a> |
  704. <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  705. <a href="Book/Gatsby">Gatsby</a> |
  706. <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  707. <a href="Book/Scarlet">Scarlet Letter</a><br/>
  708. <div class="view-animate-container">
  709. <div ng-view class="view-animate"></div>
  710. </div>
  711. <hr />
  712. <pre>$location.path() = {{main.$location.path()}}</pre>
  713. <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
  714. <pre>$route.current.params = {{main.$route.current.params}}</pre>
  715. <pre>$routeParams = {{main.$routeParams}}</pre>
  716. </div>
  717. </file>
  718. <file name="book.html">
  719. <div>
  720. controller: {{book.name}}<br />
  721. Book Id: {{book.params.bookId}}<br />
  722. </div>
  723. </file>
  724. <file name="chapter.html">
  725. <div>
  726. controller: {{chapter.name}}<br />
  727. Book Id: {{chapter.params.bookId}}<br />
  728. Chapter Id: {{chapter.params.chapterId}}
  729. </div>
  730. </file>
  731. <file name="animations.css">
  732. .view-animate-container {
  733. position:relative;
  734. height:100px!important;
  735. background:white;
  736. border:1px solid black;
  737. height:40px;
  738. overflow:hidden;
  739. }
  740. .view-animate {
  741. padding:10px;
  742. }
  743. .view-animate.ng-enter, .view-animate.ng-leave {
  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. scope[current.resolveAs || '$resolve'] = locals;
  908. link(scope);
  909. }
  910. };
  911. }
  912. })(window, window.angular);