angular-route.js 32 KB

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