angular-route.js 32 KB

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