angular-route.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. /**
  2. * @license AngularJS v1.2.17
  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. /**
  26. * @ngdoc provider
  27. * @name $routeProvider
  28. * @kind function
  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(new (angular.extend(function() {}, {prototype: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. routes[path] = angular.extend(
  146. {reloadOnSearch: true},
  147. route,
  148. path && pathRegExp(path, route)
  149. );
  150. // create redirection for trailing slashes
  151. if (path) {
  152. var redirectPath = (path[path.length-1] == '/')
  153. ? path.substr(0, path.length-1)
  154. : path +'/';
  155. routes[redirectPath] = angular.extend(
  156. {redirectTo: path},
  157. pathRegExp(redirectPath, route)
  158. );
  159. }
  160. return this;
  161. };
  162. /**
  163. * @param path {string} path
  164. * @param opts {Object} options
  165. * @return {?Object}
  166. *
  167. * @description
  168. * Normalizes the given path, returning a regular expression
  169. * and the original path.
  170. *
  171. * Inspired by pathRexp in visionmedia/express/lib/utils.js.
  172. */
  173. function pathRegExp(path, opts) {
  174. var insensitive = opts.caseInsensitiveMatch,
  175. ret = {
  176. originalPath: path,
  177. regexp: path
  178. },
  179. keys = ret.keys = [];
  180. path = path
  181. .replace(/([().])/g, '\\$1')
  182. .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){
  183. var optional = option === '?' ? option : null;
  184. var star = option === '*' ? option : null;
  185. keys.push({ name: key, optional: !!optional });
  186. slash = slash || '';
  187. return ''
  188. + (optional ? '' : slash)
  189. + '(?:'
  190. + (optional ? slash : '')
  191. + (star && '(.+?)' || '([^/]+)')
  192. + (optional || '')
  193. + ')'
  194. + (optional || '');
  195. })
  196. .replace(/([\/$\*])/g, '\\$1');
  197. ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
  198. return ret;
  199. }
  200. /**
  201. * @ngdoc method
  202. * @name $routeProvider#otherwise
  203. *
  204. * @description
  205. * Sets route definition that will be used on route change when no other route definition
  206. * is matched.
  207. *
  208. * @param {Object} params Mapping information to be assigned to `$route.current`.
  209. * @returns {Object} self
  210. */
  211. this.otherwise = function(params) {
  212. this.when(null, params);
  213. return this;
  214. };
  215. this.$get = ['$rootScope',
  216. '$location',
  217. '$routeParams',
  218. '$q',
  219. '$injector',
  220. '$http',
  221. '$templateCache',
  222. '$sce',
  223. function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) {
  224. /**
  225. * @ngdoc service
  226. * @name $route
  227. * @requires $location
  228. * @requires $routeParams
  229. *
  230. * @property {Object} current Reference to the current route definition.
  231. * The route definition contains:
  232. *
  233. * - `controller`: The controller constructor as define in route definition.
  234. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
  235. * controller instantiation. The `locals` contain
  236. * the resolved values of the `resolve` map. Additionally the `locals` also contain:
  237. *
  238. * - `$scope` - The current route scope.
  239. * - `$template` - The current route template HTML.
  240. *
  241. * @property {Object} routes Object with all route configuration Objects as its properties.
  242. *
  243. * @description
  244. * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
  245. * It watches `$location.url()` and tries to map the path to an existing route definition.
  246. *
  247. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  248. *
  249. * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
  250. *
  251. * The `$route` service is typically used in conjunction with the
  252. * {@link ngRoute.directive:ngView `ngView`} directive and the
  253. * {@link ngRoute.$routeParams `$routeParams`} service.
  254. *
  255. * @example
  256. * This example shows how changing the URL hash causes the `$route` to match a route against the
  257. * URL, and the `ngView` pulls in the partial.
  258. *
  259. * Note that this example is using {@link ng.directive:script inlined templates}
  260. * to get it working on jsfiddle as well.
  261. *
  262. * <example name="$route-service" module="ngRouteExample"
  263. * deps="angular-route.js" fixBase="true">
  264. * <file name="index.html">
  265. * <div ng-controller="MainController">
  266. * Choose:
  267. * <a href="Book/Moby">Moby</a> |
  268. * <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  269. * <a href="Book/Gatsby">Gatsby</a> |
  270. * <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  271. * <a href="Book/Scarlet">Scarlet Letter</a><br/>
  272. *
  273. * <div ng-view></div>
  274. *
  275. * <hr />
  276. *
  277. * <pre>$location.path() = {{$location.path()}}</pre>
  278. * <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
  279. * <pre>$route.current.params = {{$route.current.params}}</pre>
  280. * <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
  281. * <pre>$routeParams = {{$routeParams}}</pre>
  282. * </div>
  283. * </file>
  284. *
  285. * <file name="book.html">
  286. * controller: {{name}}<br />
  287. * Book Id: {{params.bookId}}<br />
  288. * </file>
  289. *
  290. * <file name="chapter.html">
  291. * controller: {{name}}<br />
  292. * Book Id: {{params.bookId}}<br />
  293. * Chapter Id: {{params.chapterId}}
  294. * </file>
  295. *
  296. * <file name="script.js">
  297. * angular.module('ngRouteExample', ['ngRoute'])
  298. *
  299. * .controller('MainController', function($scope, $route, $routeParams, $location) {
  300. * $scope.$route = $route;
  301. * $scope.$location = $location;
  302. * $scope.$routeParams = $routeParams;
  303. * })
  304. *
  305. * .controller('BookController', function($scope, $routeParams) {
  306. * $scope.name = "BookController";
  307. * $scope.params = $routeParams;
  308. * })
  309. *
  310. * .controller('ChapterController', function($scope, $routeParams) {
  311. * $scope.name = "ChapterController";
  312. * $scope.params = $routeParams;
  313. * })
  314. *
  315. * .config(function($routeProvider, $locationProvider) {
  316. * $routeProvider
  317. * .when('/Book/:bookId', {
  318. * templateUrl: 'book.html',
  319. * controller: 'BookController',
  320. * resolve: {
  321. * // I will cause a 1 second delay
  322. * delay: function($q, $timeout) {
  323. * var delay = $q.defer();
  324. * $timeout(delay.resolve, 1000);
  325. * return delay.promise;
  326. * }
  327. * }
  328. * })
  329. * .when('/Book/:bookId/ch/:chapterId', {
  330. * templateUrl: 'chapter.html',
  331. * controller: 'ChapterController'
  332. * });
  333. *
  334. * // configure html5 to get links working on jsfiddle
  335. * $locationProvider.html5Mode(true);
  336. * });
  337. *
  338. * </file>
  339. *
  340. * <file name="protractor.js" type="protractor">
  341. * it('should load and compile correct template', function() {
  342. * element(by.linkText('Moby: Ch1')).click();
  343. * var content = element(by.css('[ng-view]')).getText();
  344. * expect(content).toMatch(/controller\: ChapterController/);
  345. * expect(content).toMatch(/Book Id\: Moby/);
  346. * expect(content).toMatch(/Chapter Id\: 1/);
  347. *
  348. * element(by.partialLinkText('Scarlet')).click();
  349. *
  350. * content = element(by.css('[ng-view]')).getText();
  351. * expect(content).toMatch(/controller\: BookController/);
  352. * expect(content).toMatch(/Book Id\: Scarlet/);
  353. * });
  354. * </file>
  355. * </example>
  356. */
  357. /**
  358. * @ngdoc event
  359. * @name $route#$routeChangeStart
  360. * @eventType broadcast on root scope
  361. * @description
  362. * Broadcasted before a route change. At this point the route services starts
  363. * resolving all of the dependencies needed for the route change to occur.
  364. * Typically this involves fetching the view template as well as any dependencies
  365. * defined in `resolve` route property. Once all of the dependencies are resolved
  366. * `$routeChangeSuccess` is fired.
  367. *
  368. * @param {Object} angularEvent Synthetic event object.
  369. * @param {Route} next Future route information.
  370. * @param {Route} current Current route information.
  371. */
  372. /**
  373. * @ngdoc event
  374. * @name $route#$routeChangeSuccess
  375. * @eventType broadcast on root scope
  376. * @description
  377. * Broadcasted after a route dependencies are resolved.
  378. * {@link ngRoute.directive:ngView ngView} listens for the directive
  379. * to instantiate the controller and render the view.
  380. *
  381. * @param {Object} angularEvent Synthetic event object.
  382. * @param {Route} current Current route information.
  383. * @param {Route|Undefined} previous Previous route information, or undefined if current is
  384. * first route entered.
  385. */
  386. /**
  387. * @ngdoc event
  388. * @name $route#$routeChangeError
  389. * @eventType broadcast on root scope
  390. * @description
  391. * Broadcasted if any of the resolve promises are rejected.
  392. *
  393. * @param {Object} angularEvent Synthetic event object
  394. * @param {Route} current Current route information.
  395. * @param {Route} previous Previous route information.
  396. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
  397. */
  398. /**
  399. * @ngdoc event
  400. * @name $route#$routeUpdate
  401. * @eventType broadcast on root scope
  402. * @description
  403. *
  404. * The `reloadOnSearch` property has been set to false, and we are reusing the same
  405. * instance of the Controller.
  406. */
  407. var forceReload = false,
  408. $route = {
  409. routes: routes,
  410. /**
  411. * @ngdoc method
  412. * @name $route#reload
  413. *
  414. * @description
  415. * Causes `$route` service to reload the current route even if
  416. * {@link ng.$location $location} hasn't changed.
  417. *
  418. * As a result of that, {@link ngRoute.directive:ngView ngView}
  419. * creates new scope, reinstantiates the controller.
  420. */
  421. reload: function() {
  422. forceReload = true;
  423. $rootScope.$evalAsync(updateRoute);
  424. }
  425. };
  426. $rootScope.$on('$locationChangeSuccess', updateRoute);
  427. return $route;
  428. /////////////////////////////////////////////////////
  429. /**
  430. * @param on {string} current url
  431. * @param route {Object} route regexp to match the url against
  432. * @return {?Object}
  433. *
  434. * @description
  435. * Check if the route matches the current url.
  436. *
  437. * Inspired by match in
  438. * visionmedia/express/lib/router/router.js.
  439. */
  440. function switchRouteMatcher(on, route) {
  441. var keys = route.keys,
  442. params = {};
  443. if (!route.regexp) return null;
  444. var m = route.regexp.exec(on);
  445. if (!m) return null;
  446. for (var i = 1, len = m.length; i < len; ++i) {
  447. var key = keys[i - 1];
  448. var val = 'string' == typeof m[i]
  449. ? decodeURIComponent(m[i])
  450. : m[i];
  451. if (key && val) {
  452. params[key.name] = val;
  453. }
  454. }
  455. return params;
  456. }
  457. function updateRoute() {
  458. var next = parseRoute(),
  459. last = $route.current;
  460. if (next && last && next.$$route === last.$$route
  461. && angular.equals(next.pathParams, last.pathParams)
  462. && !next.reloadOnSearch && !forceReload) {
  463. last.params = next.params;
  464. angular.copy(last.params, $routeParams);
  465. $rootScope.$broadcast('$routeUpdate', last);
  466. } else if (next || last) {
  467. forceReload = false;
  468. $rootScope.$broadcast('$routeChangeStart', next, last);
  469. $route.current = next;
  470. if (next) {
  471. if (next.redirectTo) {
  472. if (angular.isString(next.redirectTo)) {
  473. $location.path(interpolate(next.redirectTo, next.params)).search(next.params)
  474. .replace();
  475. } else {
  476. $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
  477. .replace();
  478. }
  479. }
  480. }
  481. $q.when(next).
  482. then(function() {
  483. if (next) {
  484. var locals = angular.extend({}, next.resolve),
  485. template, templateUrl;
  486. angular.forEach(locals, function(value, key) {
  487. locals[key] = angular.isString(value) ?
  488. $injector.get(value) : $injector.invoke(value);
  489. });
  490. if (angular.isDefined(template = next.template)) {
  491. if (angular.isFunction(template)) {
  492. template = template(next.params);
  493. }
  494. } else if (angular.isDefined(templateUrl = next.templateUrl)) {
  495. if (angular.isFunction(templateUrl)) {
  496. templateUrl = templateUrl(next.params);
  497. }
  498. templateUrl = $sce.getTrustedResourceUrl(templateUrl);
  499. if (angular.isDefined(templateUrl)) {
  500. next.loadedTemplateUrl = templateUrl;
  501. template = $http.get(templateUrl, {cache: $templateCache}).
  502. then(function(response) { return response.data; });
  503. }
  504. }
  505. if (angular.isDefined(template)) {
  506. locals['$template'] = template;
  507. }
  508. return $q.all(locals);
  509. }
  510. }).
  511. // after route change
  512. then(function(locals) {
  513. if (next == $route.current) {
  514. if (next) {
  515. next.locals = locals;
  516. angular.copy(next.params, $routeParams);
  517. }
  518. $rootScope.$broadcast('$routeChangeSuccess', next, last);
  519. }
  520. }, function(error) {
  521. if (next == $route.current) {
  522. $rootScope.$broadcast('$routeChangeError', next, last, error);
  523. }
  524. });
  525. }
  526. }
  527. /**
  528. * @returns {Object} the current active route, by matching it against the URL
  529. */
  530. function parseRoute() {
  531. // Match a route
  532. var params, match;
  533. angular.forEach(routes, function(route, path) {
  534. if (!match && (params = switchRouteMatcher($location.path(), route))) {
  535. match = inherit(route, {
  536. params: angular.extend({}, $location.search(), params),
  537. pathParams: params});
  538. match.$$route = route;
  539. }
  540. });
  541. // No route matched; fallback to "otherwise" route
  542. return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
  543. }
  544. /**
  545. * @returns {string} interpolation of the redirect path with the parameters
  546. */
  547. function interpolate(string, params) {
  548. var result = [];
  549. angular.forEach((string||'').split(':'), function(segment, i) {
  550. if (i === 0) {
  551. result.push(segment);
  552. } else {
  553. var segmentMatch = segment.match(/(\w+)(.*)/);
  554. var key = segmentMatch[1];
  555. result.push(params[key]);
  556. result.push(segmentMatch[2] || '');
  557. delete params[key];
  558. }
  559. });
  560. return result.join('');
  561. }
  562. }];
  563. }
  564. ngRouteModule.provider('$routeParams', $RouteParamsProvider);
  565. /**
  566. * @ngdoc service
  567. * @name $routeParams
  568. * @requires $route
  569. *
  570. * @description
  571. * The `$routeParams` service allows you to retrieve the current set of route parameters.
  572. *
  573. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  574. *
  575. * The route parameters are a combination of {@link ng.$location `$location`}'s
  576. * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
  577. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
  578. *
  579. * In case of parameter name collision, `path` params take precedence over `search` params.
  580. *
  581. * The service guarantees that the identity of the `$routeParams` object will remain unchanged
  582. * (but its properties will likely change) even when a route change occurs.
  583. *
  584. * Note that the `$routeParams` are only updated *after* a route change completes successfully.
  585. * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
  586. * Instead you can use `$route.current.params` to access the new route's parameters.
  587. *
  588. * @example
  589. * ```js
  590. * // Given:
  591. * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
  592. * // Route: /Chapter/:chapterId/Section/:sectionId
  593. * //
  594. * // Then
  595. * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
  596. * ```
  597. */
  598. function $RouteParamsProvider() {
  599. this.$get = function() { return {}; };
  600. }
  601. ngRouteModule.directive('ngView', ngViewFactory);
  602. ngRouteModule.directive('ngView', ngViewFillContentFactory);
  603. /**
  604. * @ngdoc directive
  605. * @name ngView
  606. * @restrict ECA
  607. *
  608. * @description
  609. * # Overview
  610. * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
  611. * including the rendered template of the current route into the main layout (`index.html`) file.
  612. * Every time the current route changes, the included view changes with it according to the
  613. * configuration of the `$route` service.
  614. *
  615. * Requires the {@link ngRoute `ngRoute`} module to be installed.
  616. *
  617. * @animations
  618. * enter - animation is used to bring new content into the browser.
  619. * leave - animation is used to animate existing content away.
  620. *
  621. * The enter and leave animation occur concurrently.
  622. *
  623. * @scope
  624. * @priority 400
  625. * @param {string=} onload Expression to evaluate whenever the view updates.
  626. *
  627. * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
  628. * $anchorScroll} to scroll the viewport after the view is updated.
  629. *
  630. * - If the attribute is not set, disable scrolling.
  631. * - If the attribute is set without value, enable scrolling.
  632. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
  633. * as an expression yields a truthy value.
  634. * @example
  635. <example name="ngView-directive" module="ngViewExample"
  636. deps="angular-route.js;angular-animate.js"
  637. animations="true" fixBase="true">
  638. <file name="index.html">
  639. <div ng-controller="MainCtrl as main">
  640. Choose:
  641. <a href="Book/Moby">Moby</a> |
  642. <a href="Book/Moby/ch/1">Moby: Ch1</a> |
  643. <a href="Book/Gatsby">Gatsby</a> |
  644. <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
  645. <a href="Book/Scarlet">Scarlet Letter</a><br/>
  646. <div class="view-animate-container">
  647. <div ng-view class="view-animate"></div>
  648. </div>
  649. <hr />
  650. <pre>$location.path() = {{main.$location.path()}}</pre>
  651. <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
  652. <pre>$route.current.params = {{main.$route.current.params}}</pre>
  653. <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre>
  654. <pre>$routeParams = {{main.$routeParams}}</pre>
  655. </div>
  656. </file>
  657. <file name="book.html">
  658. <div>
  659. controller: {{book.name}}<br />
  660. Book Id: {{book.params.bookId}}<br />
  661. </div>
  662. </file>
  663. <file name="chapter.html">
  664. <div>
  665. controller: {{chapter.name}}<br />
  666. Book Id: {{chapter.params.bookId}}<br />
  667. Chapter Id: {{chapter.params.chapterId}}
  668. </div>
  669. </file>
  670. <file name="animations.css">
  671. .view-animate-container {
  672. position:relative;
  673. height:100px!important;
  674. position:relative;
  675. background:white;
  676. border:1px solid black;
  677. height:40px;
  678. overflow:hidden;
  679. }
  680. .view-animate {
  681. padding:10px;
  682. }
  683. .view-animate.ng-enter, .view-animate.ng-leave {
  684. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  685. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
  686. display:block;
  687. width:100%;
  688. border-left:1px solid black;
  689. position:absolute;
  690. top:0;
  691. left:0;
  692. right:0;
  693. bottom:0;
  694. padding:10px;
  695. }
  696. .view-animate.ng-enter {
  697. left:100%;
  698. }
  699. .view-animate.ng-enter.ng-enter-active {
  700. left:0;
  701. }
  702. .view-animate.ng-leave.ng-leave-active {
  703. left:-100%;
  704. }
  705. </file>
  706. <file name="script.js">
  707. angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
  708. .config(['$routeProvider', '$locationProvider',
  709. function($routeProvider, $locationProvider) {
  710. $routeProvider
  711. .when('/Book/:bookId', {
  712. templateUrl: 'book.html',
  713. controller: 'BookCtrl',
  714. controllerAs: 'book'
  715. })
  716. .when('/Book/:bookId/ch/:chapterId', {
  717. templateUrl: 'chapter.html',
  718. controller: 'ChapterCtrl',
  719. controllerAs: 'chapter'
  720. });
  721. // configure html5 to get links working on jsfiddle
  722. $locationProvider.html5Mode(true);
  723. }])
  724. .controller('MainCtrl', ['$route', '$routeParams', '$location',
  725. function($route, $routeParams, $location) {
  726. this.$route = $route;
  727. this.$location = $location;
  728. this.$routeParams = $routeParams;
  729. }])
  730. .controller('BookCtrl', ['$routeParams', function($routeParams) {
  731. this.name = "BookCtrl";
  732. this.params = $routeParams;
  733. }])
  734. .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
  735. this.name = "ChapterCtrl";
  736. this.params = $routeParams;
  737. }]);
  738. </file>
  739. <file name="protractor.js" type="protractor">
  740. it('should load and compile correct template', function() {
  741. element(by.linkText('Moby: Ch1')).click();
  742. var content = element(by.css('[ng-view]')).getText();
  743. expect(content).toMatch(/controller\: ChapterCtrl/);
  744. expect(content).toMatch(/Book Id\: Moby/);
  745. expect(content).toMatch(/Chapter Id\: 1/);
  746. element(by.partialLinkText('Scarlet')).click();
  747. content = element(by.css('[ng-view]')).getText();
  748. expect(content).toMatch(/controller\: BookCtrl/);
  749. expect(content).toMatch(/Book Id\: Scarlet/);
  750. });
  751. </file>
  752. </example>
  753. */
  754. /**
  755. * @ngdoc event
  756. * @name ngView#$viewContentLoaded
  757. * @eventType emit on the current ngView scope
  758. * @description
  759. * Emitted every time the ngView content is reloaded.
  760. */
  761. ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
  762. function ngViewFactory( $route, $anchorScroll, $animate) {
  763. return {
  764. restrict: 'ECA',
  765. terminal: true,
  766. priority: 400,
  767. transclude: 'element',
  768. link: function(scope, $element, attr, ctrl, $transclude) {
  769. var currentScope,
  770. currentElement,
  771. previousElement,
  772. autoScrollExp = attr.autoscroll,
  773. onloadExp = attr.onload || '';
  774. scope.$on('$routeChangeSuccess', update);
  775. update();
  776. function cleanupLastView() {
  777. if(previousElement) {
  778. previousElement.remove();
  779. previousElement = null;
  780. }
  781. if(currentScope) {
  782. currentScope.$destroy();
  783. currentScope = null;
  784. }
  785. if(currentElement) {
  786. $animate.leave(currentElement, function() {
  787. previousElement = null;
  788. });
  789. previousElement = currentElement;
  790. currentElement = null;
  791. }
  792. }
  793. function update() {
  794. var locals = $route.current && $route.current.locals,
  795. template = locals && locals.$template;
  796. if (angular.isDefined(template)) {
  797. var newScope = scope.$new();
  798. var current = $route.current;
  799. // Note: This will also link all children of ng-view that were contained in the original
  800. // html. If that content contains controllers, ... they could pollute/change the scope.
  801. // However, using ng-view on an element with additional content does not make sense...
  802. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  803. // function is called before linking the content, which would apply child
  804. // directives to non existing elements.
  805. var clone = $transclude(newScope, function(clone) {
  806. $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () {
  807. if (angular.isDefined(autoScrollExp)
  808. && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  809. $anchorScroll();
  810. }
  811. });
  812. cleanupLastView();
  813. });
  814. currentElement = clone;
  815. currentScope = current.scope = newScope;
  816. currentScope.$emit('$viewContentLoaded');
  817. currentScope.$eval(onloadExp);
  818. } else {
  819. cleanupLastView();
  820. }
  821. }
  822. }
  823. };
  824. }
  825. // This directive is called during the $transclude call of the first `ngView` directive.
  826. // It will replace and compile the content of the element with the loaded template.
  827. // We need this directive so that the element content is already filled when
  828. // the link function of another directive on the same element as ngView
  829. // is called.
  830. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
  831. function ngViewFillContentFactory($compile, $controller, $route) {
  832. return {
  833. restrict: 'ECA',
  834. priority: -400,
  835. link: function(scope, $element) {
  836. var current = $route.current,
  837. locals = current.locals;
  838. $element.html(locals.$template);
  839. var link = $compile($element.contents());
  840. if (current.controller) {
  841. locals.$scope = scope;
  842. var controller = $controller(current.controller, locals);
  843. if (current.controllerAs) {
  844. scope[current.controllerAs] = controller;
  845. }
  846. $element.data('$ngControllerController', controller);
  847. $element.children().data('$ngControllerController', controller);
  848. }
  849. link(scope);
  850. }
  851. };
  852. }
  853. })(window, window.angular);