angular-route.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. /**
  2. * @license AngularJS v1.3.4
  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 sensitive
  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} newParams mapping of URL parameter names to values
  464. */
  465. updateParams: function(newParams) {
  466. if (this.current && this.current.$$route) {
  467. var searchParams = {}, self=this;
  468. angular.forEach(Object.keys(newParams), function(key) {
  469. if (!self.current.pathParams[key]) searchParams[key] = newParams[key];
  470. });
  471. newParams = angular.extend({}, this.current.params, newParams);
  472. $location.path(interpolate(this.current.$$route.originalPath, newParams));
  473. $location.search(angular.extend({}, $location.search(), searchParams));
  474. }
  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. templateUrl = $sce.getTrustedResourceUrl(templateUrl);
  563. if (angular.isDefined(templateUrl)) {
  564. nextRoute.loadedTemplateUrl = templateUrl;
  565. template = $templateRequest(templateUrl);
  566. }
  567. }
  568. if (angular.isDefined(template)) {
  569. locals['$template'] = template;
  570. }
  571. return $q.all(locals);
  572. }
  573. }).
  574. // after route change
  575. then(function(locals) {
  576. if (nextRoute == $route.current) {
  577. if (nextRoute) {
  578. nextRoute.locals = locals;
  579. angular.copy(nextRoute.params, $routeParams);
  580. }
  581. $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
  582. }
  583. }, function(error) {
  584. if (nextRoute == $route.current) {
  585. $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
  586. }
  587. });
  588. }
  589. }
  590. /**
  591. * @returns {Object} the current active route, by matching it against the URL
  592. */
  593. function parseRoute() {
  594. // Match a route
  595. var params, match;
  596. angular.forEach(routes, function(route, path) {
  597. if (!match && (params = switchRouteMatcher($location.path(), route))) {
  598. match = inherit(route, {
  599. params: angular.extend({}, $location.search(), params),
  600. pathParams: params});
  601. match.$$route = route;
  602. }
  603. });
  604. // No route matched; fallback to "otherwise" route
  605. return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
  606. }
  607. /**
  608. * @returns {string} interpolation of the redirect path with the parameters
  609. */
  610. function interpolate(string, params) {
  611. var result = [];
  612. angular.forEach((string || '').split(':'), function(segment, i) {
  613. if (i === 0) {
  614. result.push(segment);
  615. } else {
  616. var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
  617. var key = segmentMatch[1];
  618. result.push(params[key]);
  619. result.push(segmentMatch[2] || '');
  620. delete params[key];
  621. }
  622. });
  623. return result.join('');
  624. }
  625. }];
  626. }
  627. ngRouteModule.provider('$routeParams', $RouteParamsProvider);
  628. /**
  629. * @ngdoc service
  630. * @name $routeParams
  631. * @requires $route
  632. *
  633. * @description
  634. * The `$routeParams` service allows you to retrieve the current set of route parameters.
  635. *
  636. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  637. *
  638. * The route parameters are a combination of {@link ng.$location `$location`}'s
  639. * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
  640. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
  641. *
  642. * In case of parameter name collision, `path` params take precedence over `search` params.
  643. *
  644. * The service guarantees that the identity of the `$routeParams` object will remain unchanged
  645. * (but its properties will likely change) even when a route change occurs.
  646. *
  647. * Note that the `$routeParams` are only updated *after* a route change completes successfully.
  648. * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
  649. * Instead you can use `$route.current.params` to access the new route's parameters.
  650. *
  651. * @example
  652. * ```js
  653. * // Given:
  654. * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
  655. * // Route: /Chapter/:chapterId/Section/:sectionId
  656. * //
  657. * // Then
  658. * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
  659. * ```
  660. */
  661. function $RouteParamsProvider() {
  662. this.$get = function() { return {}; };
  663. }
  664. ngRouteModule.directive('ngView', ngViewFactory);
  665. ngRouteModule.directive('ngView', ngViewFillContentFactory);
  666. /**
  667. * @ngdoc directive
  668. * @name ngView
  669. * @restrict ECA
  670. *
  671. * @description
  672. * # Overview
  673. * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
  674. * including the rendered template of the current route into the main layout (`index.html`) file.
  675. * Every time the current route changes, the included view changes with it according to the
  676. * configuration of the `$route` service.
  677. *
  678. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  679. *
  680. * @animations
  681. * enter - animation is used to bring new content into the browser.
  682. * leave - animation is used to animate existing content away.
  683. *
  684. * The enter and leave animation occur concurrently.
  685. *
  686. * @scope
  687. * @priority 400
  688. * @param {string=} onload Expression to evaluate whenever the view updates.
  689. *
  690. * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
  691. * $anchorScroll} to scroll the viewport after the view is updated.
  692. *
  693. * - If the attribute is not set, disable scrolling.
  694. * - If the attribute is set without value, enable scrolling.
  695. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
  696. * as an expression yields a truthy value.
  697. * @example
  698. <example name="ngView-directive" module="ngViewExample"
  699. deps="angular-route.js;angular-animate.js"
  700. animations="true" fixBase="true">
  701. <file name="index.html">
  702. <div ng-controller="MainCtrl as main">
  703. Choose:
  704. <a href="Book/Moby">Moby</a> |
  705. <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  706. <a href="Book/Gatsby">Gatsby</a> |
  707. <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  708. <a href="Book/Scarlet">Scarlet Letter</a><br/>
  709. <div class="view-animate-container">
  710. <div ng-view class="view-animate"></div>
  711. </div>
  712. <hr />
  713. <pre>$location.path() = {{main.$location.path()}}</pre>
  714. <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
  715. <pre>$route.current.params = {{main.$route.current.params}}</pre>
  716. <pre>$routeParams = {{main.$routeParams}}</pre>
  717. </div>
  718. </file>
  719. <file name="book.html">
  720. <div>
  721. controller: {{book.name}}<br />
  722. Book Id: {{book.params.bookId}}<br />
  723. </div>
  724. </file>
  725. <file name="chapter.html">
  726. <div>
  727. controller: {{chapter.name}}<br />
  728. Book Id: {{chapter.params.bookId}}<br />
  729. Chapter Id: {{chapter.params.chapterId}}
  730. </div>
  731. </file>
  732. <file name="animations.css">
  733. .view-animate-container {
  734. position:relative;
  735. height:100px!important;
  736. position:relative;
  737. background:white;
  738. border:1px solid black;
  739. height:40px;
  740. overflow:hidden;
  741. }
  742. .view-animate {
  743. padding:10px;
  744. }
  745. .view-animate.ng-enter, .view-animate.ng-leave {
  746. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  747. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  748. display:block;
  749. width:100%;
  750. border-left:1px solid black;
  751. position:absolute;
  752. top:0;
  753. left:0;
  754. right:0;
  755. bottom:0;
  756. padding:10px;
  757. }
  758. .view-animate.ng-enter {
  759. left:100%;
  760. }
  761. .view-animate.ng-enter.ng-enter-active {
  762. left:0;
  763. }
  764. .view-animate.ng-leave.ng-leave-active {
  765. left:-100%;
  766. }
  767. </file>
  768. <file name="script.js">
  769. angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
  770. .config(['$routeProvider', '$locationProvider',
  771. function($routeProvider, $locationProvider) {
  772. $routeProvider
  773. .when('/Book/:bookId', {
  774. templateUrl: 'book.html',
  775. controller: 'BookCtrl',
  776. controllerAs: 'book'
  777. })
  778. .when('/Book/:bookId/ch/:chapterId', {
  779. templateUrl: 'chapter.html',
  780. controller: 'ChapterCtrl',
  781. controllerAs: 'chapter'
  782. });
  783. $locationProvider.html5Mode(true);
  784. }])
  785. .controller('MainCtrl', ['$route', '$routeParams', '$location',
  786. function($route, $routeParams, $location) {
  787. this.$route = $route;
  788. this.$location = $location;
  789. this.$routeParams = $routeParams;
  790. }])
  791. .controller('BookCtrl', ['$routeParams', function($routeParams) {
  792. this.name = "BookCtrl";
  793. this.params = $routeParams;
  794. }])
  795. .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
  796. this.name = "ChapterCtrl";
  797. this.params = $routeParams;
  798. }]);
  799. </file>
  800. <file name="protractor.js" type="protractor">
  801. it('should load and compile correct template', function() {
  802. element(by.linkText('Moby: Ch1')).click();
  803. var content = element(by.css('[ng-view]')).getText();
  804. expect(content).toMatch(/controller\: ChapterCtrl/);
  805. expect(content).toMatch(/Book Id\: Moby/);
  806. expect(content).toMatch(/Chapter Id\: 1/);
  807. element(by.partialLinkText('Scarlet')).click();
  808. content = element(by.css('[ng-view]')).getText();
  809. expect(content).toMatch(/controller\: BookCtrl/);
  810. expect(content).toMatch(/Book Id\: Scarlet/);
  811. });
  812. </file>
  813. </example>
  814. */
  815. /**
  816. * @ngdoc event
  817. * @name ngView#$viewContentLoaded
  818. * @eventType emit on the current ngView scope
  819. * @description
  820. * Emitted every time the ngView content is reloaded.
  821. */
  822. ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
  823. function ngViewFactory($route, $anchorScroll, $animate) {
  824. return {
  825. restrict: 'ECA',
  826. terminal: true,
  827. priority: 400,
  828. transclude: 'element',
  829. link: function(scope, $element, attr, ctrl, $transclude) {
  830. var currentScope,
  831. currentElement,
  832. previousLeaveAnimation,
  833. autoScrollExp = attr.autoscroll,
  834. onloadExp = attr.onload || '';
  835. scope.$on('$routeChangeSuccess', update);
  836. update();
  837. function cleanupLastView() {
  838. if (previousLeaveAnimation) {
  839. $animate.cancel(previousLeaveAnimation);
  840. previousLeaveAnimation = null;
  841. }
  842. if (currentScope) {
  843. currentScope.$destroy();
  844. currentScope = null;
  845. }
  846. if (currentElement) {
  847. previousLeaveAnimation = $animate.leave(currentElement);
  848. previousLeaveAnimation.then(function() {
  849. previousLeaveAnimation = null;
  850. });
  851. currentElement = null;
  852. }
  853. }
  854. function update() {
  855. var locals = $route.current && $route.current.locals,
  856. template = locals && locals.$template;
  857. if (angular.isDefined(template)) {
  858. var newScope = scope.$new();
  859. var current = $route.current;
  860. // Note: This will also link all children of ng-view that were contained in the original
  861. // html. If that content contains controllers, ... they could pollute/change the scope.
  862. // However, using ng-view on an element with additional content does not make sense...
  863. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  864. // function is called before linking the content, which would apply child
  865. // directives to non existing elements.
  866. var clone = $transclude(newScope, function(clone) {
  867. $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
  868. if (angular.isDefined(autoScrollExp)
  869. && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  870. $anchorScroll();
  871. }
  872. });
  873. cleanupLastView();
  874. });
  875. currentElement = clone;
  876. currentScope = current.scope = newScope;
  877. currentScope.$emit('$viewContentLoaded');
  878. currentScope.$eval(onloadExp);
  879. } else {
  880. cleanupLastView();
  881. }
  882. }
  883. }
  884. };
  885. }
  886. // This directive is called during the $transclude call of the first `ngView` directive.
  887. // It will replace and compile the content of the element with the loaded template.
  888. // We need this directive so that the element content is already filled when
  889. // the link function of another directive on the same element as ngView
  890. // is called.
  891. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
  892. function ngViewFillContentFactory($compile, $controller, $route) {
  893. return {
  894. restrict: 'ECA',
  895. priority: -400,
  896. link: function(scope, $element) {
  897. var current = $route.current,
  898. locals = current.locals;
  899. $element.html(locals.$template);
  900. var link = $compile($element.contents());
  901. if (current.controller) {
  902. locals.$scope = scope;
  903. var controller = $controller(current.controller, locals);
  904. if (current.controllerAs) {
  905. scope[current.controllerAs] = controller;
  906. }
  907. $element.data('$ngControllerController', controller);
  908. $element.children().data('$ngControllerController', controller);
  909. }
  910. link(scope);
  911. }
  912. };
  913. }
  914. })(window, window.angular);