You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4231 lines
153 KiB

  1. /**
  2. * State-based routing for AngularJS
  3. * @version v0.2.13
  4. * @link http://angular-ui.github.com/
  5. * @license MIT License, http://www.opensource.org/licenses/MIT
  6. */
  7. /* commonjs package manager support (eg componentjs) */
  8. if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
  9. module.exports = 'ui.router';
  10. }
  11. (function (window, angular, undefined) {
  12. /*jshint globalstrict:true*/
  13. /*global angular:false*/
  14. 'use strict';
  15. var isDefined = angular.isDefined,
  16. isFunction = angular.isFunction,
  17. isString = angular.isString,
  18. isObject = angular.isObject,
  19. isArray = angular.isArray,
  20. forEach = angular.forEach,
  21. extend = angular.extend,
  22. copy = angular.copy;
  23. function inherit(parent, extra) {
  24. return extend(new (extend(function() {}, { prototype: parent }))(), extra);
  25. }
  26. function merge(dst) {
  27. forEach(arguments, function(obj) {
  28. if (obj !== dst) {
  29. forEach(obj, function(value, key) {
  30. if (!dst.hasOwnProperty(key)) dst[key] = value;
  31. });
  32. }
  33. });
  34. return dst;
  35. }
  36. /**
  37. * Finds the common ancestor path between two states.
  38. *
  39. * @param {Object} first The first state.
  40. * @param {Object} second The second state.
  41. * @return {Array} Returns an array of state names in descending order, not including the root.
  42. */
  43. function ancestors(first, second) {
  44. var path = [];
  45. for (var n in first.path) {
  46. if (first.path[n] !== second.path[n]) break;
  47. path.push(first.path[n]);
  48. }
  49. return path;
  50. }
  51. /**
  52. * IE8-safe wrapper for `Object.keys()`.
  53. *
  54. * @param {Object} object A JavaScript object.
  55. * @return {Array} Returns the keys of the object as an array.
  56. */
  57. function objectKeys(object) {
  58. if (Object.keys) {
  59. return Object.keys(object);
  60. }
  61. var result = [];
  62. angular.forEach(object, function(val, key) {
  63. result.push(key);
  64. });
  65. return result;
  66. }
  67. /**
  68. * IE8-safe wrapper for `Array.prototype.indexOf()`.
  69. *
  70. * @param {Array} array A JavaScript array.
  71. * @param {*} value A value to search the array for.
  72. * @return {Number} Returns the array index value of `value`, or `-1` if not present.
  73. */
  74. function indexOf(array, value) {
  75. if (Array.prototype.indexOf) {
  76. return array.indexOf(value, Number(arguments[2]) || 0);
  77. }
  78. var len = array.length >>> 0, from = Number(arguments[2]) || 0;
  79. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  80. if (from < 0) from += len;
  81. for (; from < len; from++) {
  82. if (from in array && array[from] === value) return from;
  83. }
  84. return -1;
  85. }
  86. /**
  87. * Merges a set of parameters with all parameters inherited between the common parents of the
  88. * current state and a given destination state.
  89. *
  90. * @param {Object} currentParams The value of the current state parameters ($stateParams).
  91. * @param {Object} newParams The set of parameters which will be composited with inherited params.
  92. * @param {Object} $current Internal definition of object representing the current state.
  93. * @param {Object} $to Internal definition of object representing state to transition to.
  94. */
  95. function inheritParams(currentParams, newParams, $current, $to) {
  96. var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
  97. for (var i in parents) {
  98. if (!parents[i].params) continue;
  99. parentParams = objectKeys(parents[i].params);
  100. if (!parentParams.length) continue;
  101. for (var j in parentParams) {
  102. if (indexOf(inheritList, parentParams[j]) >= 0) continue;
  103. inheritList.push(parentParams[j]);
  104. inherited[parentParams[j]] = currentParams[parentParams[j]];
  105. }
  106. }
  107. return extend({}, inherited, newParams);
  108. }
  109. /**
  110. * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
  111. *
  112. * @param {Object} a The first object.
  113. * @param {Object} b The second object.
  114. * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
  115. * it defaults to the list of keys in `a`.
  116. * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
  117. */
  118. function equalForKeys(a, b, keys) {
  119. if (!keys) {
  120. keys = [];
  121. for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
  122. }
  123. for (var i=0; i<keys.length; i++) {
  124. var k = keys[i];
  125. if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
  126. }
  127. return true;
  128. }
  129. /**
  130. * Returns the subset of an object, based on a list of keys.
  131. *
  132. * @param {Array} keys
  133. * @param {Object} values
  134. * @return {Boolean} Returns a subset of `values`.
  135. */
  136. function filterByKeys(keys, values) {
  137. var filtered = {};
  138. forEach(keys, function (name) {
  139. filtered[name] = values[name];
  140. });
  141. return filtered;
  142. }
  143. // like _.indexBy
  144. // when you know that your index values will be unique, or you want last-one-in to win
  145. function indexBy(array, propName) {
  146. var result = {};
  147. forEach(array, function(item) {
  148. result[item[propName]] = item;
  149. });
  150. return result;
  151. }
  152. // extracted from underscore.js
  153. // Return a copy of the object only containing the whitelisted properties.
  154. function pick(obj) {
  155. var copy = {};
  156. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  157. forEach(keys, function(key) {
  158. if (key in obj) copy[key] = obj[key];
  159. });
  160. return copy;
  161. }
  162. // extracted from underscore.js
  163. // Return a copy of the object omitting the blacklisted properties.
  164. function omit(obj) {
  165. var copy = {};
  166. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  167. for (var key in obj) {
  168. if (indexOf(keys, key) == -1) copy[key] = obj[key];
  169. }
  170. return copy;
  171. }
  172. function pluck(collection, key) {
  173. var result = isArray(collection) ? [] : {};
  174. forEach(collection, function(val, i) {
  175. result[i] = isFunction(key) ? key(val) : val[key];
  176. });
  177. return result;
  178. }
  179. function filter(collection, callback) {
  180. var array = isArray(collection);
  181. var result = array ? [] : {};
  182. forEach(collection, function(val, i) {
  183. if (callback(val, i)) {
  184. result[array ? result.length : i] = val;
  185. }
  186. });
  187. return result;
  188. }
  189. function map(collection, callback) {
  190. var result = isArray(collection) ? [] : {};
  191. forEach(collection, function(val, i) {
  192. result[i] = callback(val, i);
  193. });
  194. return result;
  195. }
  196. /**
  197. * @ngdoc overview
  198. * @name ui.router.util
  199. *
  200. * @description
  201. * # ui.router.util sub-module
  202. *
  203. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  204. * in your angular app (use {@link ui.router} module instead).
  205. *
  206. */
  207. angular.module('ui.router.util', ['ng']);
  208. /**
  209. * @ngdoc overview
  210. * @name ui.router.router
  211. *
  212. * @requires ui.router.util
  213. *
  214. * @description
  215. * # ui.router.router sub-module
  216. *
  217. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  218. * in your angular app (use {@link ui.router} module instead).
  219. */
  220. angular.module('ui.router.router', ['ui.router.util']);
  221. /**
  222. * @ngdoc overview
  223. * @name ui.router.state
  224. *
  225. * @requires ui.router.router
  226. * @requires ui.router.util
  227. *
  228. * @description
  229. * # ui.router.state sub-module
  230. *
  231. * This module is a dependency of the main ui.router module. Do not include this module as a dependency
  232. * in your angular app (use {@link ui.router} module instead).
  233. *
  234. */
  235. angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
  236. /**
  237. * @ngdoc overview
  238. * @name ui.router
  239. *
  240. * @requires ui.router.state
  241. *
  242. * @description
  243. * # ui.router
  244. *
  245. * ## The main module for ui.router
  246. * There are several sub-modules included with the ui.router module, however only this module is needed
  247. * as a dependency within your angular app. The other modules are for organization purposes.
  248. *
  249. * The modules are:
  250. * * ui.router - the main "umbrella" module
  251. * * ui.router.router -
  252. *
  253. * *You'll need to include **only** this module as the dependency within your angular app.*
  254. *
  255. * <pre>
  256. * <!doctype html>
  257. * <html ng-app="myApp">
  258. * <head>
  259. * <script src="js/angular.js"></script>
  260. * <!-- Include the ui-router script -->
  261. * <script src="js/angular-ui-router.min.js"></script>
  262. * <script>
  263. * // ...and add 'ui.router' as a dependency
  264. * var myApp = angular.module('myApp', ['ui.router']);
  265. * </script>
  266. * </head>
  267. * <body>
  268. * </body>
  269. * </html>
  270. * </pre>
  271. */
  272. angular.module('ui.router', ['ui.router.state']);
  273. angular.module('ui.router.compat', ['ui.router']);
  274. /**
  275. * @ngdoc object
  276. * @name ui.router.util.$resolve
  277. *
  278. * @requires $q
  279. * @requires $injector
  280. *
  281. * @description
  282. * Manages resolution of (acyclic) graphs of promises.
  283. */
  284. $Resolve.$inject = ['$q', '$injector'];
  285. function $Resolve( $q, $injector) {
  286. var VISIT_IN_PROGRESS = 1,
  287. VISIT_DONE = 2,
  288. NOTHING = {},
  289. NO_DEPENDENCIES = [],
  290. NO_LOCALS = NOTHING,
  291. NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
  292. /**
  293. * @ngdoc function
  294. * @name ui.router.util.$resolve#study
  295. * @methodOf ui.router.util.$resolve
  296. *
  297. * @description
  298. * Studies a set of invocables that are likely to be used multiple times.
  299. * <pre>
  300. * $resolve.study(invocables)(locals, parent, self)
  301. * </pre>
  302. * is equivalent to
  303. * <pre>
  304. * $resolve.resolve(invocables, locals, parent, self)
  305. * </pre>
  306. * but the former is more efficient (in fact `resolve` just calls `study`
  307. * internally).
  308. *
  309. * @param {object} invocables Invocable objects
  310. * @return {function} a function to pass in locals, parent and self
  311. */
  312. this.study = function (invocables) {
  313. if (!isObject(invocables)) throw new Error("'invocables' must be an object");
  314. var invocableKeys = objectKeys(invocables || {});
  315. // Perform a topological sort of invocables to build an ordered plan
  316. var plan = [], cycle = [], visited = {};
  317. function visit(value, key) {
  318. if (visited[key] === VISIT_DONE) return;
  319. cycle.push(key);
  320. if (visited[key] === VISIT_IN_PROGRESS) {
  321. cycle.splice(0, indexOf(cycle, key));
  322. throw new Error("Cyclic dependency: " + cycle.join(" -> "));
  323. }
  324. visited[key] = VISIT_IN_PROGRESS;
  325. if (isString(value)) {
  326. plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
  327. } else {
  328. var params = $injector.annotate(value);
  329. forEach(params, function (param) {
  330. if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
  331. });
  332. plan.push(key, value, params);
  333. }
  334. cycle.pop();
  335. visited[key] = VISIT_DONE;
  336. }
  337. forEach(invocables, visit);
  338. invocables = cycle = visited = null; // plan is all that's required
  339. function isResolve(value) {
  340. return isObject(value) && value.then && value.$$promises;
  341. }
  342. return function (locals, parent, self) {
  343. if (isResolve(locals) && self === undefined) {
  344. self = parent; parent = locals; locals = null;
  345. }
  346. if (!locals) locals = NO_LOCALS;
  347. else if (!isObject(locals)) {
  348. throw new Error("'locals' must be an object");
  349. }
  350. if (!parent) parent = NO_PARENT;
  351. else if (!isResolve(parent)) {
  352. throw new Error("'parent' must be a promise returned by $resolve.resolve()");
  353. }
  354. // To complete the overall resolution, we have to wait for the parent
  355. // promise and for the promise for each invokable in our plan.
  356. var resolution = $q.defer(),
  357. result = resolution.promise,
  358. promises = result.$$promises = {},
  359. values = extend({}, locals),
  360. wait = 1 + plan.length/3,
  361. merged = false;
  362. function done() {
  363. // Merge parent values we haven't got yet and publish our own $$values
  364. if (!--wait) {
  365. if (!merged) merge(values, parent.$$values);
  366. result.$$values = values;
  367. result.$$promises = result.$$promises || true; // keep for isResolve()
  368. delete result.$$inheritedValues;
  369. resolution.resolve(values);
  370. }
  371. }
  372. function fail(reason) {
  373. result.$$failure = reason;
  374. resolution.reject(reason);
  375. }
  376. // Short-circuit if parent has already failed
  377. if (isDefined(parent.$$failure)) {
  378. fail(parent.$$failure);
  379. return result;
  380. }
  381. if (parent.$$inheritedValues) {
  382. merge(values, omit(parent.$$inheritedValues, invocableKeys));
  383. }
  384. // Merge parent values if the parent has already resolved, or merge
  385. // parent promises and wait if the parent resolve is still in progress.
  386. extend(promises, parent.$$promises);
  387. if (parent.$$values) {
  388. merged = merge(values, omit(parent.$$values, invocableKeys));
  389. result.$$inheritedValues = omit(parent.$$values, invocableKeys);
  390. done();
  391. } else {
  392. if (parent.$$inheritedValues) {
  393. result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
  394. }
  395. parent.then(done, fail);
  396. }
  397. // Process each invocable in the plan, but ignore any where a local of the same name exists.
  398. for (var i=0, ii=plan.length; i<ii; i+=3) {
  399. if (locals.hasOwnProperty(plan[i])) done();
  400. else invoke(plan[i], plan[i+1], plan[i+2]);
  401. }
  402. function invoke(key, invocable, params) {
  403. // Create a deferred for this invocation. Failures will propagate to the resolution as well.
  404. var invocation = $q.defer(), waitParams = 0;
  405. function onfailure(reason) {
  406. invocation.reject(reason);
  407. fail(reason);
  408. }
  409. // Wait for any parameter that we have a promise for (either from parent or from this
  410. // resolve; in that case study() will have made sure it's ordered before us in the plan).
  411. forEach(params, function (dep) {
  412. if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
  413. waitParams++;
  414. promises[dep].then(function (result) {
  415. values[dep] = result;
  416. if (!(--waitParams)) proceed();
  417. }, onfailure);
  418. }
  419. });
  420. if (!waitParams) proceed();
  421. function proceed() {
  422. if (isDefined(result.$$failure)) return;
  423. try {
  424. invocation.resolve($injector.invoke(invocable, self, values));
  425. invocation.promise.then(function (result) {
  426. values[key] = result;
  427. done();
  428. }, onfailure);
  429. } catch (e) {
  430. onfailure(e);
  431. }
  432. }
  433. // Publish promise synchronously; invocations further down in the plan may depend on it.
  434. promises[key] = invocation.promise;
  435. }
  436. return result;
  437. };
  438. };
  439. /**
  440. * @ngdoc function
  441. * @name ui.router.util.$resolve#resolve
  442. * @methodOf ui.router.util.$resolve
  443. *
  444. * @description
  445. * Resolves a set of invocables. An invocable is a function to be invoked via
  446. * `$injector.invoke()`, and can have an arbitrary number of dependencies.
  447. * An invocable can either return a value directly,
  448. * or a `$q` promise. If a promise is returned it will be resolved and the
  449. * resulting value will be used instead. Dependencies of invocables are resolved
  450. * (in this order of precedence)
  451. *
  452. * - from the specified `locals`
  453. * - from another invocable that is part of this `$resolve` call
  454. * - from an invocable that is inherited from a `parent` call to `$resolve`
  455. * (or recursively
  456. * - from any ancestor `$resolve` of that parent).
  457. *
  458. * The return value of `$resolve` is a promise for an object that contains
  459. * (in this order of precedence)
  460. *
  461. * - any `locals` (if specified)
  462. * - the resolved return values of all injectables
  463. * - any values inherited from a `parent` call to `$resolve` (if specified)
  464. *
  465. * The promise will resolve after the `parent` promise (if any) and all promises
  466. * returned by injectables have been resolved. If any invocable
  467. * (or `$injector.invoke`) throws an exception, or if a promise returned by an
  468. * invocable is rejected, the `$resolve` promise is immediately rejected with the
  469. * same error. A rejection of a `parent` promise (if specified) will likewise be
  470. * propagated immediately. Once the `$resolve` promise has been rejected, no
  471. * further invocables will be called.
  472. *
  473. * Cyclic dependencies between invocables are not permitted and will caues `$resolve`
  474. * to throw an error. As a special case, an injectable can depend on a parameter
  475. * with the same name as the injectable, which will be fulfilled from the `parent`
  476. * injectable of the same name. This allows inherited values to be decorated.
  477. * Note that in this case any other injectable in the same `$resolve` with the same
  478. * dependency would see the decorated value, not the inherited value.
  479. *
  480. * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
  481. * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
  482. * exception.
  483. *
  484. * Invocables are invoked eagerly as soon as all dependencies are available.
  485. * This is true even for dependencies inherited from a `parent` call to `$resolve`.
  486. *
  487. * As a special case, an invocable can be a string, in which case it is taken to
  488. * be a service name to be passed to `$injector.get()`. This is supported primarily
  489. * for backwards-compatibility with the `resolve` property of `$routeProvider`
  490. * routes.
  491. *
  492. * @param {object} invocables functions to invoke or
  493. * `$injector` services to fetch.
  494. * @param {object} locals values to make available to the injectables
  495. * @param {object} parent a promise returned by another call to `$resolve`.
  496. * @param {object} self the `this` for the invoked methods
  497. * @return {object} Promise for an object that contains the resolved return value
  498. * of all invocables, as well as any inherited and local values.
  499. */
  500. this.resolve = function (invocables, locals, parent, self) {
  501. return this.study(invocables)(locals, parent, self);
  502. };
  503. }
  504. angular.module('ui.router.util').service('$resolve', $Resolve);
  505. /**
  506. * @ngdoc object
  507. * @name ui.router.util.$templateFactory
  508. *
  509. * @requires $http
  510. * @requires $templateCache
  511. * @requires $injector
  512. *
  513. * @description
  514. * Service. Manages loading of templates.
  515. */
  516. $TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
  517. function $TemplateFactory( $http, $templateCache, $injector) {
  518. /**
  519. * @ngdoc function
  520. * @name ui.router.util.$templateFactory#fromConfig
  521. * @methodOf ui.router.util.$templateFactory
  522. *
  523. * @description
  524. * Creates a template from a configuration object.
  525. *
  526. * @param {object} config Configuration object for which to load a template.
  527. * The following properties are search in the specified order, and the first one
  528. * that is defined is used to create the template:
  529. *
  530. * @param {string|object} config.template html string template or function to
  531. * load via {@link ui.router.util.$templateFactory#fromString fromString}.
  532. * @param {string|object} config.templateUrl url to load or a function returning
  533. * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
  534. * @param {Function} config.templateProvider function to invoke via
  535. * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
  536. * @param {object} params Parameters to pass to the template function.
  537. * @param {object} locals Locals to pass to `invoke` if the template is loaded
  538. * via a `templateProvider`. Defaults to `{ params: params }`.
  539. *
  540. * @return {string|object} The template html as a string, or a promise for
  541. * that string,or `null` if no template is configured.
  542. */
  543. this.fromConfig = function (config, params, locals) {
  544. return (
  545. isDefined(config.template) ? this.fromString(config.template, params) :
  546. isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
  547. isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
  548. null
  549. );
  550. };
  551. /**
  552. * @ngdoc function
  553. * @name ui.router.util.$templateFactory#fromString
  554. * @methodOf ui.router.util.$templateFactory
  555. *
  556. * @description
  557. * Creates a template from a string or a function returning a string.
  558. *
  559. * @param {string|object} template html template as a string or function that
  560. * returns an html template as a string.
  561. * @param {object} params Parameters to pass to the template function.
  562. *
  563. * @return {string|object} The template html as a string, or a promise for that
  564. * string.
  565. */
  566. this.fromString = function (template, params) {
  567. return isFunction(template) ? template(params) : template;
  568. };
  569. /**
  570. * @ngdoc function
  571. * @name ui.router.util.$templateFactory#fromUrl
  572. * @methodOf ui.router.util.$templateFactory
  573. *
  574. * @description
  575. * Loads a template from the a URL via `$http` and `$templateCache`.
  576. *
  577. * @param {string|Function} url url of the template to load, or a function
  578. * that returns a url.
  579. * @param {Object} params Parameters to pass to the url function.
  580. * @return {string|Promise.<string>} The template html as a string, or a promise
  581. * for that string.
  582. */
  583. this.fromUrl = function (url, params) {
  584. if (isFunction(url)) url = url(params);
  585. if (url == null) return null;
  586. else return $http
  587. .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
  588. .then(function(response) { return response.data; });
  589. };
  590. /**
  591. * @ngdoc function
  592. * @name ui.router.util.$templateFactory#fromProvider
  593. * @methodOf ui.router.util.$templateFactory
  594. *
  595. * @description
  596. * Creates a template by invoking an injectable provider function.
  597. *
  598. * @param {Function} provider Function to invoke via `$injector.invoke`
  599. * @param {Object} params Parameters for the template.
  600. * @param {Object} locals Locals to pass to `invoke`. Defaults to
  601. * `{ params: params }`.
  602. * @return {string|Promise.<string>} The template html as a string, or a promise
  603. * for that string.
  604. */
  605. this.fromProvider = function (provider, params, locals) {
  606. return $injector.invoke(provider, null, locals || { params: params });
  607. };
  608. }
  609. angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
  610. var $$UMFP; // reference to $UrlMatcherFactoryProvider
  611. /**
  612. * @ngdoc object
  613. * @name ui.router.util.type:UrlMatcher
  614. *
  615. * @description
  616. * Matches URLs against patterns and extracts named parameters from the path or the search
  617. * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
  618. * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
  619. * do not influence whether or not a URL is matched, but their values are passed through into
  620. * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
  621. *
  622. * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
  623. * syntax, which optionally allows a regular expression for the parameter to be specified:
  624. *
  625. * * `':'` name - colon placeholder
  626. * * `'*'` name - catch-all placeholder
  627. * * `'{' name '}'` - curly placeholder
  628. * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
  629. * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
  630. *
  631. * Parameter names may contain only word characters (latin letters, digits, and underscore) and
  632. * must be unique within the pattern (across both path and search parameters). For colon
  633. * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
  634. * number of characters other than '/'. For catch-all placeholders the path parameter matches
  635. * any number of characters.
  636. *
  637. * Examples:
  638. *
  639. * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
  640. * trailing slashes, and patterns have to match the entire path, not just a prefix.
  641. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
  642. * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
  643. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
  644. * * `'/user/{id:[^/]*}'` - Same as the previous example.
  645. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
  646. * parameter consists of 1 to 8 hex digits.
  647. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
  648. * path into the parameter 'path'.
  649. * * `'/files/*path'` - ditto.
  650. * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
  651. * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
  652. *
  653. * @param {string} pattern The pattern to compile into a matcher.
  654. * @param {Object} config A configuration object hash:
  655. * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
  656. * an existing UrlMatcher
  657. *
  658. * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
  659. * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.
  660. *
  661. * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
  662. * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
  663. * non-null) will start with this prefix.
  664. *
  665. * @property {string} source The pattern that was passed into the constructor
  666. *
  667. * @property {string} sourcePath The path portion of the source property
  668. *
  669. * @property {string} sourceSearch The search portion of the source property
  670. *
  671. * @property {string} regex The constructed regex that will be used to match against the url when
  672. * it is time to determine which url will match.
  673. *
  674. * @returns {Object} New `UrlMatcher` object
  675. */
  676. function UrlMatcher(pattern, config, parentMatcher) {
  677. config = extend({ params: {} }, isObject(config) ? config : {});
  678. // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
  679. // '*' name
  680. // ':' name
  681. // '{' name '}'
  682. // '{' name ':' regexp '}'
  683. // The regular expression is somewhat complicated due to the need to allow curly braces
  684. // inside the regular expression. The placeholder regexp breaks down as follows:
  685. // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
  686. // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
  687. // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
  688. // [^{}\\]+ - anything other than curly braces or backslash
  689. // \\. - a backslash escape
  690. // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
  691. var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  692. searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  693. compiled = '^', last = 0, m,
  694. segments = this.segments = [],
  695. parentParams = parentMatcher ? parentMatcher.params : {},
  696. params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
  697. paramNames = [];
  698. function addParameter(id, type, config, location) {
  699. paramNames.push(id);
  700. if (parentParams[id]) return parentParams[id];
  701. if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
  702. if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
  703. params[id] = new $$UMFP.Param(id, type, config, location);
  704. return params[id];
  705. }
  706. function quoteRegExp(string, pattern, squash) {
  707. var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
  708. if (!pattern) return result;
  709. switch(squash) {
  710. case false: surroundPattern = ['(', ')']; break;
  711. case true: surroundPattern = ['?(', ')?']; break;
  712. default: surroundPattern = ['(' + squash + "|", ')?']; break;
  713. }
  714. return result + surroundPattern[0] + pattern + surroundPattern[1];
  715. }
  716. this.source = pattern;
  717. // Split into static segments separated by path parameter placeholders.
  718. // The number of segments is always 1 more than the number of parameters.
  719. function matchDetails(m, isSearch) {
  720. var id, regexp, segment, type, cfg, arrayMode;
  721. id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
  722. cfg = config.params[id];
  723. segment = pattern.substring(last, m.index);
  724. regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
  725. type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp) });
  726. return {
  727. id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
  728. };
  729. }
  730. var p, param, segment;
  731. while ((m = placeholder.exec(pattern))) {
  732. p = matchDetails(m, false);
  733. if (p.segment.indexOf('?') >= 0) break; // we're into the search part
  734. param = addParameter(p.id, p.type, p.cfg, "path");
  735. compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);
  736. segments.push(p.segment);
  737. last = placeholder.lastIndex;
  738. }
  739. segment = pattern.substring(last);
  740. // Find any search parameter names and remove them from the last segment
  741. var i = segment.indexOf('?');
  742. if (i >= 0) {
  743. var search = this.sourceSearch = segment.substring(i);
  744. segment = segment.substring(0, i);
  745. this.sourcePath = pattern.substring(0, last + i);
  746. if (search.length > 0) {
  747. last = 0;
  748. while ((m = searchPlaceholder.exec(search))) {
  749. p = matchDetails(m, true);
  750. param = addParameter(p.id, p.type, p.cfg, "search");
  751. last = placeholder.lastIndex;
  752. // check if ?&
  753. }
  754. }
  755. } else {
  756. this.sourcePath = pattern;
  757. this.sourceSearch = '';
  758. }
  759. compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
  760. segments.push(segment);
  761. this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
  762. this.prefix = segments[0];
  763. this.$$paramNames = paramNames;
  764. }
  765. /**
  766. * @ngdoc function
  767. * @name ui.router.util.type:UrlMatcher#concat
  768. * @methodOf ui.router.util.type:UrlMatcher
  769. *
  770. * @description
  771. * Returns a new matcher for a pattern constructed by appending the path part and adding the
  772. * search parameters of the specified pattern to this pattern. The current pattern is not
  773. * modified. This can be understood as creating a pattern for URLs that are relative to (or
  774. * suffixes of) the current pattern.
  775. *
  776. * @example
  777. * The following two matchers are equivalent:
  778. * <pre>
  779. * new UrlMatcher('/user/{id}?q').concat('/details?date');
  780. * new UrlMatcher('/user/{id}/details?q&date');
  781. * </pre>
  782. *
  783. * @param {string} pattern The pattern to append.
  784. * @param {Object} config An object hash of the configuration for the matcher.
  785. * @returns {UrlMatcher} A matcher for the concatenated pattern.
  786. */
  787. UrlMatcher.prototype.concat = function (pattern, config) {
  788. // Because order of search parameters is irrelevant, we can add our own search
  789. // parameters to the end of the new pattern. Parse the new pattern by itself
  790. // and then join the bits together, but it's much easier to do this on a string level.
  791. var defaultConfig = {
  792. caseInsensitive: $$UMFP.caseInsensitive(),
  793. strict: $$UMFP.strictMode(),
  794. squash: $$UMFP.defaultSquashPolicy()
  795. };
  796. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
  797. };
  798. UrlMatcher.prototype.toString = function () {
  799. return this.source;
  800. };
  801. /**
  802. * @ngdoc function
  803. * @name ui.router.util.type:UrlMatcher#exec
  804. * @methodOf ui.router.util.type:UrlMatcher
  805. *
  806. * @description
  807. * Tests the specified path against this matcher, and returns an object containing the captured
  808. * parameter values, or null if the path does not match. The returned object contains the values
  809. * of any search parameters that are mentioned in the pattern, but their value may be null if
  810. * they are not present in `searchParams`. This means that search parameters are always treated
  811. * as optional.
  812. *
  813. * @example
  814. * <pre>
  815. * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
  816. * x: '1', q: 'hello'
  817. * });
  818. * // returns { id: 'bob', q: 'hello', r: null }
  819. * </pre>
  820. *
  821. * @param {string} path The URL path to match, e.g. `$location.path()`.
  822. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
  823. * @returns {Object} The captured parameter values.
  824. */
  825. UrlMatcher.prototype.exec = function (path, searchParams) {
  826. var m = this.regexp.exec(path);
  827. if (!m) return null;
  828. searchParams = searchParams || {};
  829. var paramNames = this.parameters(), nTotal = paramNames.length,
  830. nPath = this.segments.length - 1,
  831. values = {}, i, j, cfg, paramName;
  832. if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
  833. function decodePathArray(string) {
  834. function reverseString(str) { return str.split("").reverse().join(""); }
  835. function unquoteDashes(str) { return str.replace(/\\-/, "-"); }
  836. var split = reverseString(string).split(/-(?!\\)/);
  837. var allReversed = map(split, reverseString);
  838. return map(allReversed, unquoteDashes).reverse();
  839. }
  840. for (i = 0; i < nPath; i++) {
  841. paramName = paramNames[i];
  842. var param = this.params[paramName];
  843. var paramVal = m[i+1];
  844. // if the param value matches a pre-replace pair, replace the value before decoding.
  845. for (j = 0; j < param.replace; j++) {
  846. if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
  847. }
  848. if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
  849. values[paramName] = param.value(paramVal);
  850. }
  851. for (/**/; i < nTotal; i++) {
  852. paramName = paramNames[i];
  853. values[paramName] = this.params[paramName].value(searchParams[paramName]);
  854. }
  855. return values;
  856. };
  857. /**
  858. * @ngdoc function
  859. * @name ui.router.util.type:UrlMatcher#parameters
  860. * @methodOf ui.router.util.type:UrlMatcher
  861. *
  862. * @description
  863. * Returns the names of all path and search parameters of this pattern in an unspecified order.
  864. *
  865. * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
  866. * pattern has no parameters, an empty array is returned.
  867. */
  868. UrlMatcher.prototype.parameters = function (param) {
  869. if (!isDefined(param)) return this.$$paramNames;
  870. return this.params[param] || null;
  871. };
  872. /**
  873. * @ngdoc function
  874. * @name ui.router.util.type:UrlMatcher#validate
  875. * @methodOf ui.router.util.type:UrlMatcher
  876. *
  877. * @description
  878. * Checks an object hash of parameters to validate their correctness according to the parameter
  879. * types of this `UrlMatcher`.
  880. *
  881. * @param {Object} params The object hash of parameters to validate.
  882. * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
  883. */
  884. UrlMatcher.prototype.validates = function (params) {
  885. return this.params.$$validates(params);
  886. };
  887. /**
  888. * @ngdoc function
  889. * @name ui.router.util.type:UrlMatcher#format
  890. * @methodOf ui.router.util.type:UrlMatcher
  891. *
  892. * @description
  893. * Creates a URL that matches this pattern by substituting the specified values
  894. * for the path and search parameters. Null values for path parameters are
  895. * treated as empty strings.
  896. *
  897. * @example
  898. * <pre>
  899. * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
  900. * // returns '/user/bob?q=yes'
  901. * </pre>
  902. *
  903. * @param {Object} values the values to substitute for the parameters in this pattern.
  904. * @returns {string} the formatted URL (path and optionally search part).
  905. */
  906. UrlMatcher.prototype.format = function (values) {
  907. values = values || {};
  908. var segments = this.segments, params = this.parameters(), paramset = this.params;
  909. if (!this.validates(values)) return null;
  910. var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
  911. function encodeDashes(str) { // Replace dashes with encoded "\-"
  912. return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
  913. }
  914. for (i = 0; i < nTotal; i++) {
  915. var isPathParam = i < nPath;
  916. var name = params[i], param = paramset[name], value = param.value(values[name]);
  917. var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
  918. var squash = isDefaultValue ? param.squash : false;
  919. var encoded = param.type.encode(value);
  920. if (isPathParam) {
  921. var nextSegment = segments[i + 1];
  922. if (squash === false) {
  923. if (encoded != null) {
  924. if (isArray(encoded)) {
  925. result += map(encoded, encodeDashes).join("-");
  926. } else {
  927. result += encodeURIComponent(encoded);
  928. }
  929. }
  930. result += nextSegment;
  931. } else if (squash === true) {
  932. var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
  933. result += nextSegment.match(capture)[1];
  934. } else if (isString(squash)) {
  935. result += squash + nextSegment;
  936. }
  937. } else {
  938. if (encoded == null || (isDefaultValue && squash !== false)) continue;
  939. if (!isArray(encoded)) encoded = [ encoded ];
  940. encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
  941. result += (search ? '&' : '?') + (name + '=' + encoded);
  942. search = true;
  943. }
  944. }
  945. return result;
  946. };
  947. /**
  948. * @ngdoc object
  949. * @name ui.router.util.type:Type
  950. *
  951. * @description
  952. * Implements an interface to define custom parameter types that can be decoded from and encoded to
  953. * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
  954. * objects when matching or formatting URLs, or comparing or validating parameter values.
  955. *
  956. * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
  957. * information on registering custom types.
  958. *
  959. * @param {Object} config A configuration object which contains the custom type definition. The object's
  960. * properties will override the default methods and/or pattern in `Type`'s public interface.
  961. * @example
  962. * <pre>
  963. * {
  964. * decode: function(val) { return parseInt(val, 10); },
  965. * encode: function(val) { return val && val.toString(); },
  966. * equals: function(a, b) { return this.is(a) && a === b; },
  967. * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
  968. * pattern: /\d+/
  969. * }
  970. * </pre>
  971. *
  972. * @property {RegExp} pattern The regular expression pattern used to match values of this type when
  973. * coming from a substring of a URL.
  974. *
  975. * @returns {Object} Returns a new `Type` object.
  976. */
  977. function Type(config) {
  978. extend(this, config);
  979. }
  980. /**
  981. * @ngdoc function
  982. * @name ui.router.util.type:Type#is
  983. * @methodOf ui.router.util.type:Type
  984. *
  985. * @description
  986. * Detects whether a value is of a particular type. Accepts a native (decoded) value
  987. * and determines whether it matches the current `Type` object.
  988. *
  989. * @param {*} val The value to check.
  990. * @param {string} key Optional. If the type check is happening in the context of a specific
  991. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
  992. * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
  993. * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
  994. */
  995. Type.prototype.is = function(val, key) {
  996. return true;
  997. };
  998. /**
  999. * @ngdoc function
  1000. * @name ui.router.util.type:Type#encode
  1001. * @methodOf ui.router.util.type:Type
  1002. *
  1003. * @description
  1004. * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
  1005. * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
  1006. * only needs to be a representation of `val` that has been coerced to a string.
  1007. *
  1008. * @param {*} val The value to encode.
  1009. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  1010. * meta-programming of `Type` objects.
  1011. * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
  1012. */
  1013. Type.prototype.encode = function(val, key) {
  1014. return val;
  1015. };
  1016. /**
  1017. * @ngdoc function
  1018. * @name ui.router.util.type:Type#decode
  1019. * @methodOf ui.router.util.type:Type
  1020. *
  1021. * @description
  1022. * Converts a parameter value (from URL string or transition param) to a custom/native value.
  1023. *
  1024. * @param {string} val The URL parameter value to decode.
  1025. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  1026. * meta-programming of `Type` objects.
  1027. * @returns {*} Returns a custom representation of the URL parameter value.
  1028. */
  1029. Type.prototype.decode = function(val, key) {
  1030. return val;
  1031. };
  1032. /**
  1033. * @ngdoc function
  1034. * @name ui.router.util.type:Type#equals
  1035. * @methodOf ui.router.util.type:Type
  1036. *
  1037. * @description
  1038. * Determines whether two decoded values are equivalent.
  1039. *
  1040. * @param {*} a A value to compare against.
  1041. * @param {*} b A value to compare against.
  1042. * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
  1043. */
  1044. Type.prototype.equals = function(a, b) {
  1045. return a == b;
  1046. };
  1047. Type.prototype.$subPattern = function() {
  1048. var sub = this.pattern.toString();
  1049. return sub.substr(1, sub.length - 2);
  1050. };
  1051. Type.prototype.pattern = /.*/;
  1052. Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
  1053. /*
  1054. * Wraps an existing custom Type as an array of Type, depending on 'mode'.
  1055. * e.g.:
  1056. * - urlmatcher pattern "/path?{queryParam[]:int}"
  1057. * - url: "/path?queryParam=1&queryParam=2
  1058. * - $stateParams.queryParam will be [1, 2]
  1059. * if `mode` is "auto", then
  1060. * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
  1061. * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
  1062. */
  1063. Type.prototype.$asArray = function(mode, isSearch) {
  1064. if (!mode) return this;
  1065. if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
  1066. return new ArrayType(this, mode);
  1067. function ArrayType(type, mode) {
  1068. function bindTo(type, callbackName) {
  1069. return function() {
  1070. return type[callbackName].apply(type, arguments);
  1071. };
  1072. }
  1073. // Wrap non-array value as array
  1074. function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
  1075. // Unwrap array value for "auto" mode. Return undefined for empty array.
  1076. function arrayUnwrap(val) {
  1077. switch(val.length) {
  1078. case 0: return undefined;
  1079. case 1: return mode === "auto" ? val[0] : val;
  1080. default: return val;
  1081. }
  1082. }
  1083. function falsey(val) { return !val; }
  1084. // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
  1085. function arrayHandler(callback, allTruthyMode) {
  1086. return function handleArray(val) {
  1087. val = arrayWrap(val);
  1088. var result = map(val, callback);
  1089. if (allTruthyMode === true)
  1090. return filter(result, falsey).length === 0;
  1091. return arrayUnwrap(result);
  1092. };
  1093. }
  1094. // Wraps type (.equals) functions to operate on each value of an array
  1095. function arrayEqualsHandler(callback) {
  1096. return function handleArray(val1, val2) {
  1097. var left = arrayWrap(val1), right = arrayWrap(val2);
  1098. if (left.length !== right.length) return false;
  1099. for (var i = 0; i < left.length; i++) {
  1100. if (!callback(left[i], right[i])) return false;
  1101. }
  1102. return true;
  1103. };
  1104. }
  1105. this.encode = arrayHandler(bindTo(type, 'encode'));
  1106. this.decode = arrayHandler(bindTo(type, 'decode'));
  1107. this.is = arrayHandler(bindTo(type, 'is'), true);
  1108. this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
  1109. this.pattern = type.pattern;
  1110. this.$arrayMode = mode;
  1111. }
  1112. };
  1113. /**
  1114. * @ngdoc object
  1115. * @name ui.router.util.$urlMatcherFactory
  1116. *
  1117. * @description
  1118. * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
  1119. * is also available to providers under the name `$urlMatcherFactoryProvider`.
  1120. */
  1121. function $UrlMatcherFactory() {
  1122. $$UMFP = this;
  1123. var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
  1124. function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
  1125. function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
  1126. // TODO: in 1.0, make string .is() return false if value is undefined by default.
  1127. // function regexpMatches(val) { /*jshint validthis:true */ return isDefined(val) && this.pattern.test(val); }
  1128. function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); }
  1129. var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
  1130. string: {
  1131. encode: valToString,
  1132. decode: valFromString,
  1133. is: regexpMatches,
  1134. pattern: /[^/]*/
  1135. },
  1136. int: {
  1137. encode: valToString,
  1138. decode: function(val) { return parseInt(val, 10); },
  1139. is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
  1140. pattern: /\d+/
  1141. },
  1142. bool: {
  1143. encode: function(val) { return val ? 1 : 0; },
  1144. decode: function(val) { return parseInt(val, 10) !== 0; },
  1145. is: function(val) { return val === true || val === false; },
  1146. pattern: /0|1/
  1147. },
  1148. date: {
  1149. encode: function (val) {
  1150. if (!this.is(val))
  1151. return undefined;
  1152. return [ val.getFullYear(),
  1153. ('0' + (val.getMonth() + 1)).slice(-2),
  1154. ('0' + val.getDate()).slice(-2)
  1155. ].join("-");
  1156. },
  1157. decode: function (val) {
  1158. if (this.is(val)) return val;
  1159. var match = this.capture.exec(val);
  1160. return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
  1161. },
  1162. is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },
  1163. equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },
  1164. pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
  1165. capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
  1166. },
  1167. json: {
  1168. encode: angular.toJson,
  1169. decode: angular.fromJson,
  1170. is: angular.isObject,
  1171. equals: angular.equals,
  1172. pattern: /[^/]*/
  1173. },
  1174. any: { // does not encode/decode
  1175. encode: angular.identity,
  1176. decode: angular.identity,
  1177. is: angular.identity,
  1178. equals: angular.equals,
  1179. pattern: /.*/
  1180. }
  1181. };
  1182. function getDefaultConfig() {
  1183. return {
  1184. strict: isStrictMode,
  1185. caseInsensitive: isCaseInsensitive
  1186. };
  1187. }
  1188. function isInjectable(value) {
  1189. return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
  1190. }
  1191. /**
  1192. * [Internal] Get the default value of a parameter, which may be an injectable function.
  1193. */
  1194. $UrlMatcherFactory.$$getDefaultValue = function(config) {
  1195. if (!isInjectable(config.value)) return config.value;
  1196. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  1197. return injector.invoke(config.value);
  1198. };
  1199. /**
  1200. * @ngdoc function
  1201. * @name ui.router.util.$urlMatcherFactory#caseInsensitive
  1202. * @methodOf ui.router.util.$urlMatcherFactory
  1203. *
  1204. * @description
  1205. * Defines whether URL matching should be case sensitive (the default behavior), or not.
  1206. *
  1207. * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
  1208. * @returns {boolean} the current value of caseInsensitive
  1209. */
  1210. this.caseInsensitive = function(value) {
  1211. if (isDefined(value))
  1212. isCaseInsensitive = value;
  1213. return isCaseInsensitive;
  1214. };
  1215. /**
  1216. * @ngdoc function
  1217. * @name ui.router.util.$urlMatcherFactory#strictMode
  1218. * @methodOf ui.router.util.$urlMatcherFactory
  1219. *
  1220. * @description
  1221. * Defines whether URLs should match trailing slashes, or not (the default behavior).
  1222. *
  1223. * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
  1224. * @returns {boolean} the current value of strictMode
  1225. */
  1226. this.strictMode = function(value) {
  1227. if (isDefined(value))
  1228. isStrictMode = value;
  1229. return isStrictMode;
  1230. };
  1231. /**
  1232. * @ngdoc function
  1233. * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
  1234. * @methodOf ui.router.util.$urlMatcherFactory
  1235. *
  1236. * @description
  1237. * Sets the default behavior when generating or matching URLs with default parameter values.
  1238. *
  1239. * @param {string} value A string that defines the default parameter URL squashing behavior.
  1240. * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
  1241. * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
  1242. * parameter is surrounded by slashes, squash (remove) one slash from the URL
  1243. * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
  1244. * the parameter value from the URL and replace it with this string.
  1245. */
  1246. this.defaultSquashPolicy = function(value) {
  1247. if (!isDefined(value)) return defaultSquashPolicy;
  1248. if (value !== true && value !== false && !isString(value))
  1249. throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
  1250. defaultSquashPolicy = value;
  1251. return value;
  1252. };
  1253. /**
  1254. * @ngdoc function
  1255. * @name ui.router.util.$urlMatcherFactory#compile
  1256. * @methodOf ui.router.util.$urlMatcherFactory
  1257. *
  1258. * @description
  1259. * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
  1260. *
  1261. * @param {string} pattern The URL pattern.
  1262. * @param {Object} config The config object hash.
  1263. * @returns {UrlMatcher} The UrlMatcher.
  1264. */
  1265. this.compile = function (pattern, config) {
  1266. return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
  1267. };
  1268. /**
  1269. * @ngdoc function
  1270. * @name ui.router.util.$urlMatcherFactory#isMatcher
  1271. * @methodOf ui.router.util.$urlMatcherFactory
  1272. *
  1273. * @description
  1274. * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
  1275. *
  1276. * @param {Object} object The object to perform the type check against.
  1277. * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
  1278. * implementing all the same methods.
  1279. */
  1280. this.isMatcher = function (o) {
  1281. if (!isObject(o)) return false;
  1282. var result = true;
  1283. forEach(UrlMatcher.prototype, function(val, name) {
  1284. if (isFunction(val)) {
  1285. result = result && (isDefined(o[name]) && isFunction(o[name]));
  1286. }
  1287. });
  1288. return result;
  1289. };
  1290. /**
  1291. * @ngdoc function
  1292. * @name ui.router.util.$urlMatcherFactory#type
  1293. * @methodOf ui.router.util.$urlMatcherFactory
  1294. *
  1295. * @description
  1296. * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
  1297. * generate URLs with typed parameters.
  1298. *
  1299. * @param {string} name The type name.
  1300. * @param {Object|Function} definition The type definition. See
  1301. * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  1302. * @param {Object|Function} definitionFn (optional) A function that is injected before the app
  1303. * runtime starts. The result of this function is merged into the existing `definition`.
  1304. * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  1305. *
  1306. * @returns {Object} Returns `$urlMatcherFactoryProvider`.
  1307. *
  1308. * @example
  1309. * This is a simple example of a custom type that encodes and decodes items from an
  1310. * array, using the array index as the URL-encoded value:
  1311. *
  1312. * <pre>
  1313. * var list = ['John', 'Paul', 'George', 'Ringo'];
  1314. *
  1315. * $urlMatcherFactoryProvider.type('listItem', {
  1316. * encode: function(item) {
  1317. * // Represent the list item in the URL using its corresponding index
  1318. * return list.indexOf(item);
  1319. * },
  1320. * decode: function(item) {
  1321. * // Look up the list item by index
  1322. * return list[parseInt(item, 10)];
  1323. * },
  1324. * is: function(item) {
  1325. * // Ensure the item is valid by checking to see that it appears
  1326. * // in the list
  1327. * return list.indexOf(item) > -1;
  1328. * }
  1329. * });
  1330. *
  1331. * $stateProvider.state('list', {
  1332. * url: "/list/{item:listItem}",
  1333. * controller: function($scope, $stateParams) {
  1334. * console.log($stateParams.item);
  1335. * }
  1336. * });
  1337. *
  1338. * // ...
  1339. *
  1340. * // Changes URL to '/list/3', logs "Ringo" to the console
  1341. * $state.go('list', { item: "Ringo" });
  1342. * </pre>
  1343. *
  1344. * This is a more complex example of a type that relies on dependency injection to
  1345. * interact with services, and uses the parameter name from the URL to infer how to
  1346. * handle encoding and decoding parameter values:
  1347. *
  1348. * <pre>
  1349. * // Defines a custom type that gets a value from a service,
  1350. * // where each service gets different types of values from
  1351. * // a backend API:
  1352. * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
  1353. *
  1354. * // Matches up services to URL parameter names
  1355. * var services = {
  1356. * user: Users,
  1357. * post: Posts
  1358. * };
  1359. *
  1360. * return {
  1361. * encode: function(object) {
  1362. * // Represent the object in the URL using its unique ID
  1363. * return object.id;
  1364. * },
  1365. * decode: function(value, key) {
  1366. * // Look up the object by ID, using the parameter
  1367. * // name (key) to call the correct service
  1368. * return services[key].findById(value);
  1369. * },
  1370. * is: function(object, key) {
  1371. * // Check that object is a valid dbObject
  1372. * return angular.isObject(object) && object.id && services[key];
  1373. * }
  1374. * equals: function(a, b) {
  1375. * // Check the equality of decoded objects by comparing
  1376. * // their unique IDs
  1377. * return a.id === b.id;
  1378. * }
  1379. * };
  1380. * });
  1381. *
  1382. * // In a config() block, you can then attach URLs with
  1383. * // type-annotated parameters:
  1384. * $stateProvider.state('users', {
  1385. * url: "/users",
  1386. * // ...
  1387. * }).state('users.item', {
  1388. * url: "/{user:dbObject}",
  1389. * controller: function($scope, $stateParams) {
  1390. * // $stateParams.user will now be an object returned from
  1391. * // the Users service
  1392. * },
  1393. * // ...
  1394. * });
  1395. * </pre>
  1396. */
  1397. this.type = function (name, definition, definitionFn) {
  1398. if (!isDefined(definition)) return $types[name];
  1399. if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
  1400. $types[name] = new Type(extend({ name: name }, definition));
  1401. if (definitionFn) {
  1402. typeQueue.push({ name: name, def: definitionFn });
  1403. if (!enqueue) flushTypeQueue();
  1404. }
  1405. return this;
  1406. };
  1407. // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
  1408. function flushTypeQueue() {
  1409. while(typeQueue.length) {
  1410. var type = typeQueue.shift();
  1411. if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
  1412. angular.extend($types[type.name], injector.invoke(type.def));
  1413. }
  1414. }
  1415. // Register default types. Store them in the prototype of $types.
  1416. forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
  1417. $types = inherit($types, {});
  1418. /* No need to document $get, since it returns this */
  1419. this.$get = ['$injector', function ($injector) {
  1420. injector = $injector;
  1421. enqueue = false;
  1422. flushTypeQueue();
  1423. forEach(defaultTypes, function(type, name) {
  1424. if (!$types[name]) $types[name] = new Type(type);
  1425. });
  1426. return this;
  1427. }];
  1428. this.Param = function Param(id, type, config, location) {
  1429. var self = this;
  1430. config = unwrapShorthand(config);
  1431. type = getType(config, type, location);
  1432. var arrayMode = getArrayMode();
  1433. type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
  1434. if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
  1435. config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
  1436. var isOptional = config.value !== undefined;
  1437. var squash = getSquashPolicy(config, isOptional);
  1438. var replace = getReplace(config, arrayMode, isOptional, squash);
  1439. function unwrapShorthand(config) {
  1440. var keys = isObject(config) ? objectKeys(config) : [];
  1441. var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
  1442. indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
  1443. if (isShorthand) config = { value: config };
  1444. config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
  1445. return config;
  1446. }
  1447. function getType(config, urlType, location) {
  1448. if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
  1449. if (urlType) return urlType;
  1450. if (!config.type) return (location === "config" ? $types.any : $types.string);
  1451. return config.type instanceof Type ? config.type : new Type(config.type);
  1452. }
  1453. // array config: param name (param[]) overrides default settings. explicit config overrides param name.
  1454. function getArrayMode() {
  1455. var arrayDefaults = { array: (location === "search" ? "auto" : false) };
  1456. var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
  1457. return extend(arrayDefaults, arrayParamNomenclature, config).array;
  1458. }
  1459. /**
  1460. * returns false, true, or the squash value to indicate the "default parameter url squash policy".
  1461. */
  1462. function getSquashPolicy(config, isOptional) {
  1463. var squash = config.squash;
  1464. if (!isOptional || squash === false) return false;
  1465. if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
  1466. if (squash === true || isString(squash)) return squash;
  1467. throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
  1468. }
  1469. function getReplace(config, arrayMode, isOptional, squash) {
  1470. var replace, configuredKeys, defaultPolicy = [
  1471. { from: "", to: (isOptional || arrayMode ? undefined : "") },
  1472. { from: null, to: (isOptional || arrayMode ? undefined : "") }
  1473. ];
  1474. replace = isArray(config.replace) ? config.replace : [];
  1475. if (isString(squash))
  1476. replace.push({ from: squash, to: undefined });
  1477. configuredKeys = map(replace, function(item) { return item.from; } );
  1478. return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
  1479. }
  1480. /**
  1481. * [Internal] Get the default value of a parameter, which may be an injectable function.
  1482. */
  1483. function $$getDefaultValue() {
  1484. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  1485. return injector.invoke(config.$$fn);
  1486. }
  1487. /**
  1488. * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
  1489. * default value, which may be the result of an injectable function.
  1490. */
  1491. function $value(value) {
  1492. function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
  1493. function $replace(value) {
  1494. var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
  1495. return replacement.length ? replacement[0] : value;
  1496. }
  1497. value = $replace(value);
  1498. return isDefined(value) ? self.type.decode(value) : $$getDefaultValue();
  1499. }
  1500. function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
  1501. extend(this, {
  1502. id: id,
  1503. type: type,
  1504. location: location,
  1505. array: arrayMode,
  1506. squash: squash,
  1507. replace: replace,
  1508. isOptional: isOptional,
  1509. value: $value,
  1510. dynamic: undefined,
  1511. config: config,
  1512. toString: toString
  1513. });
  1514. };
  1515. function ParamSet(params) {
  1516. extend(this, params || {});
  1517. }
  1518. ParamSet.prototype = {
  1519. $$new: function() {
  1520. return inherit(this, extend(new ParamSet(), { $$parent: this}));
  1521. },
  1522. $$keys: function () {
  1523. var keys = [], chain = [], parent = this,
  1524. ignore = objectKeys(ParamSet.prototype);
  1525. while (parent) { chain.push(parent); parent = parent.$$parent; }
  1526. chain.reverse();
  1527. forEach(chain, function(paramset) {
  1528. forEach(objectKeys(paramset), function(key) {
  1529. if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
  1530. });
  1531. });
  1532. return keys;
  1533. },
  1534. $$values: function(paramValues) {
  1535. var values = {}, self = this;
  1536. forEach(self.$$keys(), function(key) {
  1537. values[key] = self[key].value(paramValues && paramValues[key]);
  1538. });
  1539. return values;
  1540. },
  1541. $$equals: function(paramValues1, paramValues2) {
  1542. var equal = true, self = this;
  1543. forEach(self.$$keys(), function(key) {
  1544. var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
  1545. if (!self[key].type.equals(left, right)) equal = false;
  1546. });
  1547. return equal;
  1548. },
  1549. $$validates: function $$validate(paramValues) {
  1550. var result = true, isOptional, val, param, self = this;
  1551. forEach(this.$$keys(), function(key) {
  1552. param = self[key];
  1553. val = paramValues[key];
  1554. isOptional = !val && param.isOptional;
  1555. result = result && (isOptional || !!param.type.is(val));
  1556. });
  1557. return result;
  1558. },
  1559. $$parent: undefined
  1560. };
  1561. this.ParamSet = ParamSet;
  1562. }
  1563. // Register as a provider so it's available to other providers
  1564. angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
  1565. angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
  1566. /**
  1567. * @ngdoc object
  1568. * @name ui.router.router.$urlRouterProvider
  1569. *
  1570. * @requires ui.router.util.$urlMatcherFactoryProvider
  1571. * @requires $locationProvider
  1572. *
  1573. * @description
  1574. * `$urlRouterProvider` has the responsibility of watching `$location`.
  1575. * When `$location` changes it runs through a list of rules one by one until a
  1576. * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
  1577. * a url in a state configuration. All urls are compiled into a UrlMatcher object.
  1578. *
  1579. * There are several methods on `$urlRouterProvider` that make it useful to use directly
  1580. * in your module config.
  1581. */
  1582. $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
  1583. function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
  1584. var rules = [], otherwise = null, interceptDeferred = false, listener;
  1585. // Returns a string that is a prefix of all strings matching the RegExp
  1586. function regExpPrefix(re) {
  1587. var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
  1588. return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
  1589. }
  1590. // Interpolates matched values into a String.replace()-style pattern
  1591. function interpolate(pattern, match) {
  1592. return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
  1593. return match[what === '$' ? 0 : Number(what)];
  1594. });
  1595. }
  1596. /**
  1597. * @ngdoc function
  1598. * @name ui.router.router.$urlRouterProvider#rule
  1599. * @methodOf ui.router.router.$urlRouterProvider
  1600. *
  1601. * @description
  1602. * Defines rules that are used by `$urlRouterProvider` to find matches for
  1603. * specific URLs.
  1604. *
  1605. * @example
  1606. * <pre>
  1607. * var app = angular.module('app', ['ui.router.router']);
  1608. *
  1609. * app.config(function ($urlRouterProvider) {
  1610. * // Here's an example of how you might allow case insensitive urls
  1611. * $urlRouterProvider.rule(function ($injector, $location) {
  1612. * var path = $location.path(),
  1613. * normalized = path.toLowerCase();
  1614. *
  1615. * if (path !== normalized) {
  1616. * return normalized;
  1617. * }
  1618. * });
  1619. * });
  1620. * </pre>
  1621. *
  1622. * @param {object} rule Handler function that takes `$injector` and `$location`
  1623. * services as arguments. You can use them to return a valid path as a string.
  1624. *
  1625. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  1626. */
  1627. this.rule = function (rule) {
  1628. if (!isFunction(rule)) throw new Error("'rule' must be a function");
  1629. rules.push(rule);
  1630. return this;
  1631. };
  1632. /**
  1633. * @ngdoc object
  1634. * @name ui.router.router.$urlRouterProvider#otherwise
  1635. * @methodOf ui.router.router.$urlRouterProvider
  1636. *
  1637. * @description
  1638. * Defines a path that is used when an invalid route is requested.
  1639. *
  1640. * @example
  1641. * <pre>
  1642. * var app = angular.module('app', ['ui.router.router']);
  1643. *
  1644. * app.config(function ($urlRouterProvider) {
  1645. * // if the path doesn't match any of the urls you configured
  1646. * // otherwise will take care of routing the user to the
  1647. * // specified url
  1648. * $urlRouterProvider.otherwise('/index');
  1649. *
  1650. * // Example of using function rule as param
  1651. * $urlRouterProvider.otherwise(function ($injector, $location) {
  1652. * return '/a/valid/url';
  1653. * });
  1654. * });
  1655. * </pre>
  1656. *
  1657. * @param {string|object} rule The url path you want to redirect to or a function
  1658. * rule that returns the url path. The function version is passed two params:
  1659. * `$injector` and `$location` services, and must return a url string.
  1660. *
  1661. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  1662. */
  1663. this.otherwise = function (rule) {
  1664. if (isString(rule)) {
  1665. var redirect = rule;
  1666. rule = function () { return redirect; };
  1667. }
  1668. else if (!isFunction(rule)) throw new Error("'rule' must be a function");
  1669. otherwise = rule;
  1670. return this;
  1671. };
  1672. function handleIfMatch($injector, handler, match) {
  1673. if (!match) return false;
  1674. var result = $injector.invoke(handler, handler, { $match: match });
  1675. return isDefined(result) ? result : true;
  1676. }
  1677. /**
  1678. * @ngdoc function
  1679. * @name ui.router.router.$urlRouterProvider#when
  1680. * @methodOf ui.router.router.$urlRouterProvider
  1681. *
  1682. * @description
  1683. * Registers a handler for a given url matching. if handle is a string, it is
  1684. * treated as a redirect, and is interpolated according to the syntax of match
  1685. * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
  1686. *
  1687. * If the handler is a function, it is injectable. It gets invoked if `$location`
  1688. * matches. You have the option of inject the match object as `$match`.
  1689. *
  1690. * The handler can return
  1691. *
  1692. * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
  1693. * will continue trying to find another one that matches.
  1694. * - **string** which is treated as a redirect and passed to `$location.url()`
  1695. * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
  1696. *
  1697. * @example
  1698. * <pre>
  1699. * var app = angular.module('app', ['ui.router.router']);
  1700. *
  1701. * app.config(function ($urlRouterProvider) {
  1702. * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
  1703. * if ($state.$current.navigable !== state ||
  1704. * !equalForKeys($match, $stateParams) {
  1705. * $state.transitionTo(state, $match, false);
  1706. * }
  1707. * });
  1708. * });
  1709. * </pre>
  1710. *
  1711. * @param {string|object} what The incoming path that you want to redirect.
  1712. * @param {string|object} handler The path you want to redirect your user to.
  1713. */
  1714. this.when = function (what, handler) {
  1715. var redirect, handlerIsString = isString(handler);
  1716. if (isString(what)) what = $urlMatcherFactory.compile(what);
  1717. if (!handlerIsString && !isFunction(handler) && !isArray(handler))
  1718. throw new Error("invalid 'handler' in when()");
  1719. var strategies = {
  1720. matcher: function (what, handler) {
  1721. if (handlerIsString) {
  1722. redirect = $urlMatcherFactory.compile(handler);
  1723. handler = ['$match', function ($match) { return redirect.format($match); }];
  1724. }
  1725. return extend(function ($injector, $location) {
  1726. return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
  1727. }, {
  1728. prefix: isString(what.prefix) ? what.prefix : ''
  1729. });
  1730. },
  1731. regex: function (what, handler) {
  1732. if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
  1733. if (handlerIsString) {
  1734. redirect = handler;
  1735. handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
  1736. }
  1737. return extend(function ($injector, $location) {
  1738. return handleIfMatch($injector, handler, what.exec($location.path()));
  1739. }, {
  1740. prefix: regExpPrefix(what)
  1741. });
  1742. }
  1743. };
  1744. var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
  1745. for (var n in check) {
  1746. if (check[n]) return this.rule(strategies[n](what, handler));
  1747. }
  1748. throw new Error("invalid 'what' in when()");
  1749. };
  1750. /**
  1751. * @ngdoc function
  1752. * @name ui.router.router.$urlRouterProvider#deferIntercept
  1753. * @methodOf ui.router.router.$urlRouterProvider
  1754. *
  1755. * @description
  1756. * Disables (or enables) deferring location change interception.
  1757. *
  1758. * If you wish to customize the behavior of syncing the URL (for example, if you wish to
  1759. * defer a transition but maintain the current URL), call this method at configuration time.
  1760. * Then, at run time, call `$urlRouter.listen()` after you have configured your own
  1761. * `$locationChangeSuccess` event handler.
  1762. *
  1763. * @example
  1764. * <pre>
  1765. * var app = angular.module('app', ['ui.router.router']);
  1766. *
  1767. * app.config(function ($urlRouterProvider) {
  1768. *
  1769. * // Prevent $urlRouter from automatically intercepting URL changes;
  1770. * // this allows you to configure custom behavior in between
  1771. * // location changes and route synchronization:
  1772. * $urlRouterProvider.deferIntercept();
  1773. *
  1774. * }).run(function ($rootScope, $urlRouter, UserService) {
  1775. *
  1776. * $rootScope.$on('$locationChangeSuccess', function(e) {
  1777. * // UserService is an example service for managing user state
  1778. * if (UserService.isLoggedIn()) return;
  1779. *
  1780. * // Prevent $urlRouter's default handler from firing
  1781. * e.preventDefault();
  1782. *
  1783. * UserService.handleLogin().then(function() {
  1784. * // Once the user has logged in, sync the current URL
  1785. * // to the router:
  1786. * $urlRouter.sync();
  1787. * });
  1788. * });
  1789. *
  1790. * // Configures $urlRouter's listener *after* your custom listener
  1791. * $urlRouter.listen();
  1792. * });
  1793. * </pre>
  1794. *
  1795. * @param {boolean} defer Indicates whether to defer location change interception. Passing
  1796. no parameter is equivalent to `true`.
  1797. */
  1798. this.deferIntercept = function (defer) {
  1799. if (defer === undefined) defer = true;
  1800. interceptDeferred = defer;
  1801. };
  1802. /**
  1803. * @ngdoc object
  1804. * @name ui.router.router.$urlRouter
  1805. *
  1806. * @requires $location
  1807. * @requires $rootScope
  1808. * @requires $injector
  1809. * @requires $browser
  1810. *
  1811. * @description
  1812. *
  1813. */
  1814. this.$get = $get;
  1815. $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
  1816. function $get( $location, $rootScope, $injector, $browser) {
  1817. var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
  1818. function appendBasePath(url, isHtml5, absolute) {
  1819. if (baseHref === '/') return url;
  1820. if (isHtml5) return baseHref.slice(0, -1) + url;
  1821. if (absolute) return baseHref.slice(1) + url;
  1822. return url;
  1823. }
  1824. // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
  1825. function update(evt) {
  1826. if (evt && evt.defaultPrevented) return;
  1827. var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
  1828. lastPushedUrl = undefined;
  1829. if (ignoreUpdate) return true;
  1830. function check(rule) {
  1831. var handled = rule($injector, $location);
  1832. if (!handled) return false;
  1833. if (isString(handled)) $location.replace().url(handled);
  1834. return true;
  1835. }
  1836. var n = rules.length, i;
  1837. for (i = 0; i < n; i++) {
  1838. if (check(rules[i])) return;
  1839. }
  1840. // always check otherwise last to allow dynamic updates to the set of rules
  1841. if (otherwise) check(otherwise);
  1842. }
  1843. function listen() {
  1844. listener = listener || $rootScope.$on('$locationChangeSuccess', update);
  1845. return listener;
  1846. }
  1847. if (!interceptDeferred) listen();
  1848. return {
  1849. /**
  1850. * @ngdoc function
  1851. * @name ui.router.router.$urlRouter#sync
  1852. * @methodOf ui.router.router.$urlRouter
  1853. *
  1854. * @description
  1855. * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
  1856. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
  1857. * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
  1858. * with the transition by calling `$urlRouter.sync()`.
  1859. *
  1860. * @example
  1861. * <pre>
  1862. * angular.module('app', ['ui.router'])
  1863. * .run(function($rootScope, $urlRouter) {
  1864. * $rootScope.$on('$locationChangeSuccess', function(evt) {
  1865. * // Halt state change from even starting
  1866. * evt.preventDefault();
  1867. * // Perform custom logic
  1868. * var meetsRequirement = ...
  1869. * // Continue with the update and state transition if logic allows
  1870. * if (meetsRequirement) $urlRouter.sync();
  1871. * });
  1872. * });
  1873. * </pre>
  1874. */
  1875. sync: function() {
  1876. update();
  1877. },
  1878. listen: function() {
  1879. return listen();
  1880. },
  1881. update: function(read) {
  1882. if (read) {
  1883. location = $location.url();
  1884. return;
  1885. }
  1886. if ($location.url() === location) return;
  1887. $location.url(location);
  1888. $location.replace();
  1889. },
  1890. push: function(urlMatcher, params, options) {
  1891. $location.url(urlMatcher.format(params || {}));
  1892. lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
  1893. if (options && options.replace) $location.replace();
  1894. },
  1895. /**
  1896. * @ngdoc function
  1897. * @name ui.router.router.$urlRouter#href
  1898. * @methodOf ui.router.router.$urlRouter
  1899. *
  1900. * @description
  1901. * A URL generation method that returns the compiled URL for a given
  1902. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
  1903. *
  1904. * @example
  1905. * <pre>
  1906. * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
  1907. * person: "bob"
  1908. * });
  1909. * // $bob == "/about/bob";
  1910. * </pre>
  1911. *
  1912. * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
  1913. * @param {object=} params An object of parameter values to fill the matcher's required parameters.
  1914. * @param {object=} options Options object. The options are:
  1915. *
  1916. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  1917. *
  1918. * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
  1919. */
  1920. href: function(urlMatcher, params, options) {
  1921. if (!urlMatcher.validates(params)) return null;
  1922. var isHtml5 = $locationProvider.html5Mode();
  1923. if (angular.isObject(isHtml5)) {
  1924. isHtml5 = isHtml5.enabled;
  1925. }
  1926. var url = urlMatcher.format(params);
  1927. options = options || {};
  1928. if (!isHtml5 && url !== null) {
  1929. url = "#" + $locationProvider.hashPrefix() + url;
  1930. }
  1931. url = appendBasePath(url, isHtml5, options.absolute);
  1932. if (!options.absolute || !url) {
  1933. return url;
  1934. }
  1935. var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
  1936. port = (port === 80 || port === 443 ? '' : ':' + port);
  1937. return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
  1938. }
  1939. };
  1940. }
  1941. }
  1942. angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
  1943. /**
  1944. * @ngdoc object
  1945. * @name ui.router.state.$stateProvider
  1946. *
  1947. * @requires ui.router.router.$urlRouterProvider
  1948. * @requires ui.router.util.$urlMatcherFactoryProvider
  1949. *
  1950. * @description
  1951. * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
  1952. * on state.
  1953. *
  1954. * A state corresponds to a "place" in the application in terms of the overall UI and
  1955. * navigation. A state describes (via the controller / template / view properties) what
  1956. * the UI looks like and does at that place.
  1957. *
  1958. * States often have things in common, and the primary way of factoring out these
  1959. * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
  1960. * nested states.
  1961. *
  1962. * The `$stateProvider` provides interfaces to declare these states for your app.
  1963. */
  1964. $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
  1965. function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
  1966. var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
  1967. // Builds state properties from definition passed to registerState()
  1968. var stateBuilder = {
  1969. // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
  1970. // state.children = [];
  1971. // if (parent) parent.children.push(state);
  1972. parent: function(state) {
  1973. if (isDefined(state.parent) && state.parent) return findState(state.parent);
  1974. // regex matches any valid composite state name
  1975. // would match "contact.list" but not "contacts"
  1976. var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
  1977. return compositeName ? findState(compositeName[1]) : root;
  1978. },
  1979. // inherit 'data' from parent and override by own values (if any)
  1980. data: function(state) {
  1981. if (state.parent && state.parent.data) {
  1982. state.data = state.self.data = extend({}, state.parent.data, state.data);
  1983. }
  1984. return state.data;
  1985. },
  1986. // Build a URLMatcher if necessary, either via a relative or absolute URL
  1987. url: function(state) {
  1988. var url = state.url, config = { params: state.params || {} };
  1989. if (isString(url)) {
  1990. if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
  1991. return (state.parent.navigable || root).url.concat(url, config);
  1992. }
  1993. if (!url || $urlMatcherFactory.isMatcher(url)) return url;
  1994. throw new Error("Invalid url '" + url + "' in state '" + state + "'");
  1995. },
  1996. // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
  1997. navigable: function(state) {
  1998. return state.url ? state : (state.parent ? state.parent.navigable : null);
  1999. },
  2000. // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
  2001. ownParams: function(state) {
  2002. var params = state.url && state.url.params || new $$UMFP.ParamSet();
  2003. forEach(state.params || {}, function(config, id) {
  2004. if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
  2005. });
  2006. return params;
  2007. },
  2008. // Derive parameters for this state and ensure they're a super-set of parent's parameters
  2009. params: function(state) {
  2010. return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
  2011. },
  2012. // If there is no explicit multi-view configuration, make one up so we don't have
  2013. // to handle both cases in the view directive later. Note that having an explicit
  2014. // 'views' property will mean the default unnamed view properties are ignored. This
  2015. // is also a good time to resolve view names to absolute names, so everything is a
  2016. // straight lookup at link time.
  2017. views: function(state) {
  2018. var views = {};
  2019. forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
  2020. if (name.indexOf('@') < 0) name += '@' + state.parent.name;
  2021. views[name] = view;
  2022. });
  2023. return views;
  2024. },
  2025. // Keep a full path from the root down to this state as this is needed for state activation.
  2026. path: function(state) {
  2027. return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
  2028. },
  2029. // Speed up $state.contains() as it's used a lot
  2030. includes: function(state) {
  2031. var includes = state.parent ? extend({}, state.parent.includes) : {};
  2032. includes[state.name] = true;
  2033. return includes;
  2034. },
  2035. $delegates: {}
  2036. };
  2037. function isRelative(stateName) {
  2038. return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
  2039. }
  2040. function findState(stateOrName, base) {
  2041. if (!stateOrName) return undefined;
  2042. var isStr = isString(stateOrName),
  2043. name = isStr ? stateOrName : stateOrName.name,
  2044. path = isRelative(name);
  2045. if (path) {
  2046. if (!base) throw new Error("No reference point given for path '" + name + "'");
  2047. base = findState(base);
  2048. var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
  2049. for (; i < pathLength; i++) {
  2050. if (rel[i] === "" && i === 0) {
  2051. current = base;
  2052. continue;
  2053. }
  2054. if (rel[i] === "^") {
  2055. if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
  2056. current = current.parent;
  2057. continue;
  2058. }
  2059. break;
  2060. }
  2061. rel = rel.slice(i).join(".");
  2062. name = current.name + (current.name && rel ? "." : "") + rel;
  2063. }
  2064. var state = states[name];
  2065. if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
  2066. return state;
  2067. }
  2068. return undefined;
  2069. }
  2070. function queueState(parentName, state) {
  2071. if (!queue[parentName]) {
  2072. queue[parentName] = [];
  2073. }
  2074. queue[parentName].push(state);
  2075. }
  2076. function flushQueuedChildren(parentName) {
  2077. var queued = queue[parentName] || [];
  2078. while(queued.length) {
  2079. registerState(queued.shift());
  2080. }
  2081. }
  2082. function registerState(state) {
  2083. // Wrap a new object around the state so we can store our private details easily.
  2084. state = inherit(state, {
  2085. self: state,
  2086. resolve: state.resolve || {},
  2087. toString: function() { return this.name; }
  2088. });
  2089. var name = state.name;
  2090. if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
  2091. if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
  2092. // Get parent name
  2093. var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
  2094. : (isString(state.parent)) ? state.parent
  2095. : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
  2096. : '';
  2097. // If parent is not registered yet, add state to queue and register later
  2098. if (parentName && !states[parentName]) {
  2099. return queueState(parentName, state.self);
  2100. }
  2101. for (var key in stateBuilder) {
  2102. if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
  2103. }
  2104. states[name] = state;
  2105. // Register the state in the global state list and with $urlRouter if necessary.
  2106. if (!state[abstractKey] && state.url) {
  2107. $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
  2108. if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
  2109. $state.transitionTo(state, $match, { inherit: true, location: false });
  2110. }
  2111. }]);
  2112. }
  2113. // Register any queued children
  2114. flushQueuedChildren(name);
  2115. return state;
  2116. }
  2117. // Checks text to see if it looks like a glob.
  2118. function isGlob (text) {
  2119. return text.indexOf('*') > -1;
  2120. }
  2121. // Returns true if glob matches current $state name.
  2122. function doesStateMatchGlob (glob) {
  2123. var globSegments = glob.split('.'),
  2124. segments = $state.$current.name.split('.');
  2125. //match greedy starts
  2126. if (globSegments[0] === '**') {
  2127. segments = segments.slice(indexOf(segments, globSegments[1]));
  2128. segments.unshift('**');
  2129. }
  2130. //match greedy ends
  2131. if (globSegments[globSegments.length - 1] === '**') {
  2132. segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
  2133. segments.push('**');
  2134. }
  2135. if (globSegments.length != segments.length) {
  2136. return false;
  2137. }
  2138. //match single stars
  2139. for (var i = 0, l = globSegments.length; i < l; i++) {
  2140. if (globSegments[i] === '*') {
  2141. segments[i] = '*';
  2142. }
  2143. }
  2144. return segments.join('') === globSegments.join('');
  2145. }
  2146. // Implicit root state that is always active
  2147. root = registerState({
  2148. name: '',
  2149. url: '^',
  2150. views: null,
  2151. 'abstract': true
  2152. });
  2153. root.navigable = null;
  2154. /**
  2155. * @ngdoc function
  2156. * @name ui.router.state.$stateProvider#decorator
  2157. * @methodOf ui.router.state.$stateProvider
  2158. *
  2159. * @description
  2160. * Allows you to extend (carefully) or override (at your own peril) the
  2161. * `stateBuilder` object used internally by `$stateProvider`. This can be used
  2162. * to add custom functionality to ui-router, for example inferring templateUrl
  2163. * based on the state name.
  2164. *
  2165. * When passing only a name, it returns the current (original or decorated) builder
  2166. * function that matches `name`.
  2167. *
  2168. * The builder functions that can be decorated are listed below. Though not all
  2169. * necessarily have a good use case for decoration, that is up to you to decide.
  2170. *
  2171. * In addition, users can attach custom decorators, which will generate new
  2172. * properties within the state's internal definition. There is currently no clear
  2173. * use-case for this beyond accessing internal states (i.e. $state.$current),
  2174. * however, expect this to become increasingly relevant as we introduce additional
  2175. * meta-programming features.
  2176. *
  2177. * **Warning**: Decorators should not be interdependent because the order of
  2178. * execution of the builder functions in non-deterministic. Builder functions
  2179. * should only be dependent on the state definition object and super function.
  2180. *
  2181. *
  2182. * Existing builder functions and current return values:
  2183. *
  2184. * - **parent** `{object}` - returns the parent state object.
  2185. * - **data** `{object}` - returns state data, including any inherited data that is not
  2186. * overridden by own values (if any).
  2187. * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
  2188. * or `null`.
  2189. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
  2190. * navigable).
  2191. * - **params** `{object}` - returns an array of state params that are ensured to
  2192. * be a super-set of parent's params.
  2193. * - **views** `{object}` - returns a views object where each key is an absolute view
  2194. * name (i.e. "viewName@stateName") and each value is the config object
  2195. * (template, controller) for the view. Even when you don't use the views object
  2196. * explicitly on a state config, one is still created for you internally.
  2197. * So by decorating this builder function you have access to decorating template
  2198. * and controller properties.
  2199. * - **ownParams** `{object}` - returns an array of params that belong to the state,
  2200. * not including any params defined by ancestor states.
  2201. * - **path** `{string}` - returns the full path from the root down to this state.
  2202. * Needed for state activation.
  2203. * - **includes** `{object}` - returns an object that includes every state that
  2204. * would pass a `$state.includes()` test.
  2205. *
  2206. * @example
  2207. * <pre>
  2208. * // Override the internal 'views' builder with a function that takes the state
  2209. * // definition, and a reference to the internal function being overridden:
  2210. * $stateProvider.decorator('views', function (state, parent) {
  2211. * var result = {},
  2212. * views = parent(state);
  2213. *
  2214. * angular.forEach(views, function (config, name) {
  2215. * var autoName = (state.name + '.' + name).replace('.', '/');
  2216. * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
  2217. * result[name] = config;
  2218. * });
  2219. * return result;
  2220. * });
  2221. *
  2222. * $stateProvider.state('home', {
  2223. * views: {
  2224. * 'contact.list': { controller: 'ListController' },
  2225. * 'contact.item': { controller: 'ItemController' }
  2226. * }
  2227. * });
  2228. *
  2229. * // ...
  2230. *
  2231. * $state.go('home');
  2232. * // Auto-populates list and item views with /partials/home/contact/list.html,
  2233. * // and /partials/home/contact/item.html, respectively.
  2234. * </pre>
  2235. *
  2236. * @param {string} name The name of the builder function to decorate.
  2237. * @param {object} func A function that is responsible for decorating the original
  2238. * builder function. The function receives two parameters:
  2239. *
  2240. * - `{object}` - state - The state config object.
  2241. * - `{object}` - super - The original builder function.
  2242. *
  2243. * @return {object} $stateProvider - $stateProvider instance
  2244. */
  2245. this.decorator = decorator;
  2246. function decorator(name, func) {
  2247. /*jshint validthis: true */
  2248. if (isString(name) && !isDefined(func)) {
  2249. return stateBuilder[name];
  2250. }
  2251. if (!isFunction(func) || !isString(name)) {
  2252. return this;
  2253. }
  2254. if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
  2255. stateBuilder.$delegates[name] = stateBuilder[name];
  2256. }
  2257. stateBuilder[name] = func;
  2258. return this;
  2259. }
  2260. /**
  2261. * @ngdoc function
  2262. * @name ui.router.state.$stateProvider#state
  2263. * @methodOf ui.router.state.$stateProvider
  2264. *
  2265. * @description
  2266. * Registers a state configuration under a given state name. The stateConfig object
  2267. * has the following acceptable properties.
  2268. *
  2269. * @param {string} name A unique state name, e.g. "home", "about", "contacts".
  2270. * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
  2271. * @param {object} stateConfig State configuration object.
  2272. * @param {string|function=} stateConfig.template
  2273. * <a id='template'></a>
  2274. * html template as a string or a function that returns
  2275. * an html template as a string which should be used by the uiView directives. This property
  2276. * takes precedence over templateUrl.
  2277. *
  2278. * If `template` is a function, it will be called with the following parameters:
  2279. *
  2280. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  2281. * applying the current state
  2282. *
  2283. * <pre>template:
  2284. * "<h1>inline template definition</h1>" +
  2285. * "<div ui-view></div>"</pre>
  2286. * <pre>template: function(params) {
  2287. * return "<h1>generated template</h1>"; }</pre>
  2288. * </div>
  2289. *
  2290. * @param {string|function=} stateConfig.templateUrl
  2291. * <a id='templateUrl'></a>
  2292. *
  2293. * path or function that returns a path to an html
  2294. * template that should be used by uiView.
  2295. *
  2296. * If `templateUrl` is a function, it will be called with the following parameters:
  2297. *
  2298. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  2299. * applying the current state
  2300. *
  2301. * <pre>templateUrl: "home.html"</pre>
  2302. * <pre>templateUrl: function(params) {
  2303. * return myTemplates[params.pageId]; }</pre>
  2304. *
  2305. * @param {function=} stateConfig.templateProvider
  2306. * <a id='templateProvider'></a>
  2307. * Provider function that returns HTML content string.
  2308. * <pre> templateProvider:
  2309. * function(MyTemplateService, params) {
  2310. * return MyTemplateService.getTemplate(params.pageId);
  2311. * }</pre>
  2312. *
  2313. * @param {string|function=} stateConfig.controller
  2314. * <a id='controller'></a>
  2315. *
  2316. * Controller fn that should be associated with newly
  2317. * related scope or the name of a registered controller if passed as a string.
  2318. * Optionally, the ControllerAs may be declared here.
  2319. * <pre>controller: "MyRegisteredController"</pre>
  2320. * <pre>controller:
  2321. * "MyRegisteredController as fooCtrl"}</pre>
  2322. * <pre>controller: function($scope, MyService) {
  2323. * $scope.data = MyService.getData(); }</pre>
  2324. *
  2325. * @param {function=} stateConfig.controllerProvider
  2326. * <a id='controllerProvider'></a>
  2327. *
  2328. * Injectable provider function that returns the actual controller or string.
  2329. * <pre>controllerProvider:
  2330. * function(MyResolveData) {
  2331. * if (MyResolveData.foo)
  2332. * return "FooCtrl"
  2333. * else if (MyResolveData.bar)
  2334. * return "BarCtrl";
  2335. * else return function($scope) {
  2336. * $scope.baz = "Qux";
  2337. * }
  2338. * }</pre>
  2339. *
  2340. * @param {string=} stateConfig.controllerAs
  2341. * <a id='controllerAs'></a>
  2342. *
  2343. * A controller alias name. If present the controller will be
  2344. * published to scope under the controllerAs name.
  2345. * <pre>controllerAs: "myCtrl"</pre>
  2346. *
  2347. * @param {object=} stateConfig.resolve
  2348. * <a id='resolve'></a>
  2349. *
  2350. * An optional map&lt;string, function&gt; of dependencies which
  2351. * should be injected into the controller. If any of these dependencies are promises,
  2352. * the router will wait for them all to be resolved before the controller is instantiated.
  2353. * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
  2354. * and the values of the resolved promises are injected into any controllers that reference them.
  2355. * If any of the promises are rejected the $stateChangeError event is fired.
  2356. *
  2357. * The map object is:
  2358. *
  2359. * - key - {string}: name of dependency to be injected into controller
  2360. * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
  2361. * it is injected and return value it treated as dependency. If result is a promise, it is
  2362. * resolved before its value is injected into controller.
  2363. *
  2364. * <pre>resolve: {
  2365. * myResolve1:
  2366. * function($http, $stateParams) {
  2367. * return $http.get("/api/foos/"+stateParams.fooID);
  2368. * }
  2369. * }</pre>
  2370. *
  2371. * @param {string=} stateConfig.url
  2372. * <a id='url'></a>
  2373. *
  2374. * A url fragment with optional parameters. When a state is navigated or
  2375. * transitioned to, the `$stateParams` service will be populated with any
  2376. * parameters that were passed.
  2377. *
  2378. * examples:
  2379. * <pre>url: "/home"
  2380. * url: "/users/:userid"
  2381. * url: "/books/{bookid:[a-zA-Z_-]}"
  2382. * url: "/books/{categoryid:int}"
  2383. * url: "/books/{publishername:string}/{categoryid:int}"
  2384. * url: "/messages?before&after"
  2385. * url: "/messages?{before:date}&{after:date}"</pre>
  2386. * url: "/messages/:mailboxid?{before:date}&{after:date}"
  2387. *
  2388. * @param {object=} stateConfig.views
  2389. * <a id='views'></a>
  2390. * an optional map&lt;string, object&gt; which defined multiple views, or targets views
  2391. * manually/explicitly.
  2392. *
  2393. * Examples:
  2394. *
  2395. * Targets three named `ui-view`s in the parent state's template
  2396. * <pre>views: {
  2397. * header: {
  2398. * controller: "headerCtrl",
  2399. * templateUrl: "header.html"
  2400. * }, body: {
  2401. * controller: "bodyCtrl",
  2402. * templateUrl: "body.html"
  2403. * }, footer: {
  2404. * controller: "footCtrl",
  2405. * templateUrl: "footer.html"
  2406. * }
  2407. * }</pre>
  2408. *
  2409. * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
  2410. * <pre>views: {
  2411. * 'header@top': {
  2412. * controller: "msgHeaderCtrl",
  2413. * templateUrl: "msgHeader.html"
  2414. * }, 'body': {
  2415. * controller: "messagesCtrl",
  2416. * templateUrl: "messages.html"
  2417. * }
  2418. * }</pre>
  2419. *
  2420. * @param {boolean=} [stateConfig.abstract=false]
  2421. * <a id='abstract'></a>
  2422. * An abstract state will never be directly activated,
  2423. * but can provide inherited properties to its common children states.
  2424. * <pre>abstract: true</pre>
  2425. *
  2426. * @param {function=} stateConfig.onEnter
  2427. * <a id='onEnter'></a>
  2428. *
  2429. * Callback function for when a state is entered. Good way
  2430. * to trigger an action or dispatch an event, such as opening a dialog.
  2431. * If minifying your scripts, make sure to explictly annotate this function,
  2432. * because it won't be automatically annotated by your build tools.
  2433. *
  2434. * <pre>onEnter: function(MyService, $stateParams) {
  2435. * MyService.foo($stateParams.myParam);
  2436. * }</pre>
  2437. *
  2438. * @param {function=} stateConfig.onExit
  2439. * <a id='onExit'></a>
  2440. *
  2441. * Callback function for when a state is exited. Good way to
  2442. * trigger an action or dispatch an event, such as opening a dialog.
  2443. * If minifying your scripts, make sure to explictly annotate this function,
  2444. * because it won't be automatically annotated by your build tools.
  2445. *
  2446. * <pre>onExit: function(MyService, $stateParams) {
  2447. * MyService.cleanup($stateParams.myParam);
  2448. * }</pre>
  2449. *
  2450. * @param {boolean=} [stateConfig.reloadOnSearch=true]
  2451. * <a id='reloadOnSearch'></a>
  2452. *
  2453. * If `false`, will not retrigger the same state
  2454. * just because a search/query parameter has changed (via $location.search() or $location.hash()).
  2455. * Useful for when you'd like to modify $location.search() without triggering a reload.
  2456. * <pre>reloadOnSearch: false</pre>
  2457. *
  2458. * @param {object=} stateConfig.data
  2459. * <a id='data'></a>
  2460. *
  2461. * Arbitrary data object, useful for custom configuration. The parent state's `data` is
  2462. * prototypally inherited. In other words, adding a data property to a state adds it to
  2463. * the entire subtree via prototypal inheritance.
  2464. *
  2465. * <pre>data: {
  2466. * requiredRole: 'foo'
  2467. * } </pre>
  2468. *
  2469. * @param {object=} stateConfig.params
  2470. * <a id='params'></a>
  2471. *
  2472. * A map which optionally configures parameters declared in the `url`, or
  2473. * defines additional non-url parameters. For each parameter being
  2474. * configured, add a configuration object keyed to the name of the parameter.
  2475. *
  2476. * Each parameter configuration object may contain the following properties:
  2477. *
  2478. * - ** value ** - {object|function=}: specifies the default value for this
  2479. * parameter. This implicitly sets this parameter as optional.
  2480. *
  2481. * When UI-Router routes to a state and no value is
  2482. * specified for this parameter in the URL or transition, the
  2483. * default value will be used instead. If `value` is a function,
  2484. * it will be injected and invoked, and the return value used.
  2485. *
  2486. * *Note*: `undefined` is treated as "no default value" while `null`
  2487. * is treated as "the default value is `null`".
  2488. *
  2489. * *Shorthand*: If you only need to configure the default value of the
  2490. * parameter, you may use a shorthand syntax. In the **`params`**
  2491. * map, instead mapping the param name to a full parameter configuration
  2492. * object, simply set map it to the default parameter value, e.g.:
  2493. *
  2494. * <pre>// define a parameter's default value
  2495. * params: {
  2496. * param1: { value: "defaultValue" }
  2497. * }
  2498. * // shorthand default values
  2499. * params: {
  2500. * param1: "defaultValue",
  2501. * param2: "param2Default"
  2502. * }</pre>
  2503. *
  2504. * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
  2505. * treated as an array of values. If you specified a Type, the value will be
  2506. * treated as an array of the specified Type. Note: query parameter values
  2507. * default to a special `"auto"` mode.
  2508. *
  2509. * For query parameters in `"auto"` mode, if multiple values for a single parameter
  2510. * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
  2511. * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
  2512. * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
  2513. * value (e.g.: `{ foo: '1' }`).
  2514. *
  2515. * <pre>params: {
  2516. * param1: { array: true }
  2517. * }</pre>
  2518. *
  2519. * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
  2520. * the current parameter value is the same as the default value. If `squash` is not set, it uses the
  2521. * configured default squash policy.
  2522. * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
  2523. *
  2524. * There are three squash settings:
  2525. *
  2526. * - false: The parameter's default value is not squashed. It is encoded and included in the URL
  2527. * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
  2528. * by slashes in the state's `url` declaration, then one of those slashes are omitted.
  2529. * This can allow for cleaner looking URLs.
  2530. * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
  2531. *
  2532. * <pre>params: {
  2533. * param1: {
  2534. * value: "defaultId",
  2535. * squash: true
  2536. * } }
  2537. * // squash "defaultValue" to "~"
  2538. * params: {
  2539. * param1: {
  2540. * value: "defaultValue",
  2541. * squash: "~"
  2542. * } }
  2543. * </pre>
  2544. *
  2545. *
  2546. * @example
  2547. * <pre>
  2548. * // Some state name examples
  2549. *
  2550. * // stateName can be a single top-level name (must be unique).
  2551. * $stateProvider.state("home", {});
  2552. *
  2553. * // Or it can be a nested state name. This state is a child of the
  2554. * // above "home" state.
  2555. * $stateProvider.state("home.newest", {});
  2556. *
  2557. * // Nest states as deeply as needed.
  2558. * $stateProvider.state("home.newest.abc.xyz.inception", {});
  2559. *
  2560. * // state() returns $stateProvider, so you can chain state declarations.
  2561. * $stateProvider
  2562. * .state("home", {})
  2563. * .state("about", {})
  2564. * .state("contacts", {});
  2565. * </pre>
  2566. *
  2567. */
  2568. this.state = state;
  2569. function state(name, definition) {
  2570. /*jshint validthis: true */
  2571. if (isObject(name)) definition = name;
  2572. else definition.name = name;
  2573. registerState(definition);
  2574. return this;
  2575. }
  2576. /**
  2577. * @ngdoc object
  2578. * @name ui.router.state.$state
  2579. *
  2580. * @requires $rootScope
  2581. * @requires $q
  2582. * @requires ui.router.state.$view
  2583. * @requires $injector
  2584. * @requires ui.router.util.$resolve
  2585. * @requires ui.router.state.$stateParams
  2586. * @requires ui.router.router.$urlRouter
  2587. *
  2588. * @property {object} params A param object, e.g. {sectionId: section.id)}, that
  2589. * you'd like to test against the current active state.
  2590. * @property {object} current A reference to the state's config object. However
  2591. * you passed it in. Useful for accessing custom data.
  2592. * @property {object} transition Currently pending transition. A promise that'll
  2593. * resolve or reject.
  2594. *
  2595. * @description
  2596. * `$state` service is responsible for representing states as well as transitioning
  2597. * between them. It also provides interfaces to ask for current state or even states
  2598. * you're coming from.
  2599. */
  2600. this.$get = $get;
  2601. $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
  2602. function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
  2603. var TransitionSuperseded = $q.reject(new Error('transition superseded'));
  2604. var TransitionPrevented = $q.reject(new Error('transition prevented'));
  2605. var TransitionAborted = $q.reject(new Error('transition aborted'));
  2606. var TransitionFailed = $q.reject(new Error('transition failed'));
  2607. // Handles the case where a state which is the target of a transition is not found, and the user
  2608. // can optionally retry or defer the transition
  2609. function handleRedirect(redirect, state, params, options) {
  2610. /**
  2611. * @ngdoc event
  2612. * @name ui.router.state.$state#$stateNotFound
  2613. * @eventOf ui.router.state.$state
  2614. * @eventType broadcast on root scope
  2615. * @description
  2616. * Fired when a requested state **cannot be found** using the provided state name during transition.
  2617. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
  2618. * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
  2619. * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
  2620. * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
  2621. *
  2622. * @param {Object} event Event object.
  2623. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
  2624. * @param {State} fromState Current state object.
  2625. * @param {Object} fromParams Current state params.
  2626. *
  2627. * @example
  2628. *
  2629. * <pre>
  2630. * // somewhere, assume lazy.state has not been defined
  2631. * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
  2632. *
  2633. * // somewhere else
  2634. * $scope.$on('$stateNotFound',
  2635. * function(event, unfoundState, fromState, fromParams){
  2636. * console.log(unfoundState.to); // "lazy.state"
  2637. * console.log(unfoundState.toParams); // {a:1, b:2}
  2638. * console.log(unfoundState.options); // {inherit:false} + default options
  2639. * })
  2640. * </pre>
  2641. */
  2642. var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
  2643. if (evt.defaultPrevented) {
  2644. $urlRouter.update();
  2645. return TransitionAborted;
  2646. }
  2647. if (!evt.retry) {
  2648. return null;
  2649. }
  2650. // Allow the handler to return a promise to defer state lookup retry
  2651. if (options.$retry) {
  2652. $urlRouter.update();
  2653. return TransitionFailed;
  2654. }
  2655. var retryTransition = $state.transition = $q.when(evt.retry);
  2656. retryTransition.then(function() {
  2657. if (retryTransition !== $state.transition) return TransitionSuperseded;
  2658. redirect.options.$retry = true;
  2659. return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
  2660. }, function() {
  2661. return TransitionAborted;
  2662. });
  2663. $urlRouter.update();
  2664. return retryTransition;
  2665. }
  2666. root.locals = { resolve: null, globals: { $stateParams: {} } };
  2667. $state = {
  2668. params: {},
  2669. current: root.self,
  2670. $current: root,
  2671. transition: null
  2672. };
  2673. /**
  2674. * @ngdoc function
  2675. * @name ui.router.state.$state#reload
  2676. * @methodOf ui.router.state.$state
  2677. *
  2678. * @description
  2679. * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired,
  2680. * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).
  2681. *
  2682. * @example
  2683. * <pre>
  2684. * var app angular.module('app', ['ui.router']);
  2685. *
  2686. * app.controller('ctrl', function ($scope, $state) {
  2687. * $scope.reload = function(){
  2688. * $state.reload();
  2689. * }
  2690. * });
  2691. * </pre>
  2692. *
  2693. * `reload()` is just an alias for:
  2694. * <pre>
  2695. * $state.transitionTo($state.current, $stateParams, {
  2696. * reload: true, inherit: false, notify: true
  2697. * });
  2698. * </pre>
  2699. *
  2700. * @returns {promise} A promise representing the state of the new transition. See
  2701. * {@link ui.router.state.$state#methods_go $state.go}.
  2702. */
  2703. $state.reload = function reload() {
  2704. return $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });
  2705. };
  2706. /**
  2707. * @ngdoc function
  2708. * @name ui.router.state.$state#go
  2709. * @methodOf ui.router.state.$state
  2710. *
  2711. * @description
  2712. * Convenience method for transitioning to a new state. `$state.go` calls
  2713. * `$state.transitionTo` internally but automatically sets options to
  2714. * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
  2715. * This allows you to easily use an absolute or relative to path and specify
  2716. * only the parameters you'd like to update (while letting unspecified parameters
  2717. * inherit from the currently active ancestor states).
  2718. *
  2719. * @example
  2720. * <pre>
  2721. * var app = angular.module('app', ['ui.router']);
  2722. *
  2723. * app.controller('ctrl', function ($scope, $state) {
  2724. * $scope.changeState = function () {
  2725. * $state.go('contact.detail');
  2726. * };
  2727. * });
  2728. * </pre>
  2729. * <img src='../ngdoc_assets/StateGoExamples.png'/>
  2730. *
  2731. * @param {string} to Absolute state name or relative state path. Some examples:
  2732. *
  2733. * - `$state.go('contact.detail')` - will go to the `contact.detail` state
  2734. * - `$state.go('^')` - will go to a parent state
  2735. * - `$state.go('^.sibling')` - will go to a sibling state
  2736. * - `$state.go('.child.grandchild')` - will go to grandchild state
  2737. *
  2738. * @param {object=} params A map of the parameters that will be sent to the state,
  2739. * will populate $stateParams. Any parameters that are not specified will be inherited from currently
  2740. * defined parameters. This allows, for example, going to a sibling state that shares parameters
  2741. * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
  2742. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
  2743. * will get you all current parameters, etc.
  2744. * @param {object=} options Options object. The options are:
  2745. *
  2746. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  2747. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  2748. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  2749. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  2750. * defines which state to be relative from.
  2751. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  2752. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
  2753. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  2754. * use this when you want to force a reload when *everything* is the same, including search params.
  2755. *
  2756. * @returns {promise} A promise representing the state of the new transition.
  2757. *
  2758. * Possible success values:
  2759. *
  2760. * - $state.current
  2761. *
  2762. * <br/>Possible rejection values:
  2763. *
  2764. * - 'transition superseded' - when a newer transition has been started after this one
  2765. * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
  2766. * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
  2767. * when a `$stateNotFound` `event.retry` promise errors.
  2768. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
  2769. * - *resolve error* - when an error has occurred with a `resolve`
  2770. *
  2771. */
  2772. $state.go = function go(to, params, options) {
  2773. return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
  2774. };
  2775. /**
  2776. * @ngdoc function
  2777. * @name ui.router.state.$state#transitionTo
  2778. * @methodOf ui.router.state.$state
  2779. *
  2780. * @description
  2781. * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
  2782. * uses `transitionTo` internally. `$state.go` is recommended in most situations.
  2783. *
  2784. * @example
  2785. * <pre>
  2786. * var app = angular.module('app', ['ui.router']);
  2787. *
  2788. * app.controller('ctrl', function ($scope, $state) {
  2789. * $scope.changeState = function () {
  2790. * $state.transitionTo('contact.detail');
  2791. * };
  2792. * });
  2793. * </pre>
  2794. *
  2795. * @param {string} to State name.
  2796. * @param {object=} toParams A map of the parameters that will be sent to the state,
  2797. * will populate $stateParams.
  2798. * @param {object=} options Options object. The options are:
  2799. *
  2800. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  2801. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  2802. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
  2803. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
  2804. * defines which state to be relative from.
  2805. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  2806. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
  2807. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  2808. * use this when you want to force a reload when *everything* is the same, including search params.
  2809. *
  2810. * @returns {promise} A promise representing the state of the new transition. See
  2811. * {@link ui.router.state.$state#methods_go $state.go}.
  2812. */
  2813. $state.transitionTo = function transitionTo(to, toParams, options) {
  2814. toParams = toParams || {};
  2815. options = extend({
  2816. location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
  2817. }, options || {});
  2818. var from = $state.$current, fromParams = $state.params, fromPath = from.path;
  2819. var evt, toState = findState(to, options.relative);
  2820. if (!isDefined(toState)) {
  2821. var redirect = { to: to, toParams: toParams, options: options };
  2822. var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
  2823. if (redirectResult) {
  2824. return redirectResult;
  2825. }
  2826. // Always retry once if the $stateNotFound was not prevented
  2827. // (handles either redirect changed or state lazy-definition)
  2828. to = redirect.to;
  2829. toParams = redirect.toParams;
  2830. options = redirect.options;
  2831. toState = findState(to, options.relative);
  2832. if (!isDefined(toState)) {
  2833. if (!options.relative) throw new Error("No such state '" + to + "'");
  2834. throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
  2835. }
  2836. }
  2837. if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
  2838. if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
  2839. if (!toState.params.$$validates(toParams)) return TransitionFailed;
  2840. toParams = toState.params.$$values(toParams);
  2841. to = toState;
  2842. var toPath = to.path;
  2843. // Starting from the root of the path, keep all levels that haven't changed
  2844. var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
  2845. if (!options.reload) {
  2846. while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
  2847. locals = toLocals[keep] = state.locals;
  2848. keep++;
  2849. state = toPath[keep];
  2850. }
  2851. }
  2852. // If we're going to the same state and all locals are kept, we've got nothing to do.
  2853. // But clear 'transition', as we still want to cancel any other pending transitions.
  2854. // TODO: We may not want to bump 'transition' if we're called from a location change
  2855. // that we've initiated ourselves, because we might accidentally abort a legitimate
  2856. // transition initiated from code?
  2857. if (shouldTriggerReload(to, from, locals, options)) {
  2858. if (to.self.reloadOnSearch !== false) $urlRouter.update();
  2859. $state.transition = null;
  2860. return $q.when($state.current);
  2861. }
  2862. // Filter parameters before we pass them to event handlers etc.
  2863. toParams = filterByKeys(to.params.$$keys(), toParams || {});
  2864. // Broadcast start event and cancel the transition if requested
  2865. if (options.notify) {
  2866. /**
  2867. * @ngdoc event
  2868. * @name ui.router.state.$state#$stateChangeStart
  2869. * @eventOf ui.router.state.$state
  2870. * @eventType broadcast on root scope
  2871. * @description
  2872. * Fired when the state transition **begins**. You can use `event.preventDefault()`
  2873. * to prevent the transition from happening and then the transition promise will be
  2874. * rejected with a `'transition prevented'` value.
  2875. *
  2876. * @param {Object} event Event object.
  2877. * @param {State} toState The state being transitioned to.
  2878. * @param {Object} toParams The params supplied to the `toState`.
  2879. * @param {State} fromState The current state, pre-transition.
  2880. * @param {Object} fromParams The params supplied to the `fromState`.
  2881. *
  2882. * @example
  2883. *
  2884. * <pre>
  2885. * $rootScope.$on('$stateChangeStart',
  2886. * function(event, toState, toParams, fromState, fromParams){
  2887. * event.preventDefault();
  2888. * // transitionTo() promise will be rejected with
  2889. * // a 'transition prevented' error
  2890. * })
  2891. * </pre>
  2892. */
  2893. if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
  2894. $urlRouter.update();
  2895. return TransitionPrevented;
  2896. }
  2897. }
  2898. // Resolve locals for the remaining states, but don't update any global state just
  2899. // yet -- if anything fails to resolve the current state needs to remain untouched.
  2900. // We also set up an inheritance chain for the locals here. This allows the view directive
  2901. // to quickly look up the correct definition for each view in the current state. Even
  2902. // though we create the locals object itself outside resolveState(), it is initially
  2903. // empty and gets filled asynchronously. We need to keep track of the promise for the
  2904. // (fully resolved) current locals, and pass this down the chain.
  2905. var resolved = $q.when(locals);
  2906. for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
  2907. locals = toLocals[l] = inherit(locals);
  2908. resolved = resolveState(state, toParams, state === to, resolved, locals, options);
  2909. }
  2910. // Once everything is resolved, we are ready to perform the actual transition
  2911. // and return a promise for the new state. We also keep track of what the
  2912. // current promise is, so that we can detect overlapping transitions and
  2913. // keep only the outcome of the last transition.
  2914. var transition = $state.transition = resolved.then(function () {
  2915. var l, entering, exiting;
  2916. if ($state.transition !== transition) return TransitionSuperseded;
  2917. // Exit 'from' states not kept
  2918. for (l = fromPath.length - 1; l >= keep; l--) {
  2919. exiting = fromPath[l];
  2920. if (exiting.self.onExit) {
  2921. $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
  2922. }
  2923. exiting.locals = null;
  2924. }
  2925. // Enter 'to' states not kept
  2926. for (l = keep; l < toPath.length; l++) {
  2927. entering = toPath[l];
  2928. entering.locals = toLocals[l];
  2929. if (entering.self.onEnter) {
  2930. $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
  2931. }
  2932. }
  2933. // Run it again, to catch any transitions in callbacks
  2934. if ($state.transition !== transition) return TransitionSuperseded;
  2935. // Update globals in $state
  2936. $state.$current = to;
  2937. $state.current = to.self;
  2938. $state.params = toParams;
  2939. copy($state.params, $stateParams);
  2940. $state.transition = null;
  2941. if (options.location && to.navigable) {
  2942. $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
  2943. $$avoidResync: true, replace: options.location === 'replace'
  2944. });
  2945. }
  2946. if (options.notify) {
  2947. /**
  2948. * @ngdoc event
  2949. * @name ui.router.state.$state#$stateChangeSuccess
  2950. * @eventOf ui.router.state.$state
  2951. * @eventType broadcast on root scope
  2952. * @description
  2953. * Fired once the state transition is **complete**.
  2954. *
  2955. * @param {Object} event Event object.
  2956. * @param {State} toState The state being transitioned to.
  2957. * @param {Object} toParams The params supplied to the `toState`.
  2958. * @param {State} fromState The current state, pre-transition.
  2959. * @param {Object} fromParams The params supplied to the `fromState`.
  2960. */
  2961. $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
  2962. }
  2963. $urlRouter.update(true);
  2964. return $state.current;
  2965. }, function (error) {
  2966. if ($state.transition !== transition) return TransitionSuperseded;
  2967. $state.transition = null;
  2968. /**
  2969. * @ngdoc event
  2970. * @name ui.router.state.$state#$stateChangeError
  2971. * @eventOf ui.router.state.$state
  2972. * @eventType broadcast on root scope
  2973. * @description
  2974. * Fired when an **error occurs** during transition. It's important to note that if you
  2975. * have any errors in your resolve functions (javascript errors, non-existent services, etc)
  2976. * they will not throw traditionally. You must listen for this $stateChangeError event to
  2977. * catch **ALL** errors.
  2978. *
  2979. * @param {Object} event Event object.
  2980. * @param {State} toState The state being transitioned to.
  2981. * @param {Object} toParams The params supplied to the `toState`.
  2982. * @param {State} fromState The current state, pre-transition.
  2983. * @param {Object} fromParams The params supplied to the `fromState`.
  2984. * @param {Error} error The resolve error object.
  2985. */
  2986. evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
  2987. if (!evt.defaultPrevented) {
  2988. $urlRouter.update();
  2989. }
  2990. return $q.reject(error);
  2991. });
  2992. return transition;
  2993. };
  2994. /**
  2995. * @ngdoc function
  2996. * @name ui.router.state.$state#is
  2997. * @methodOf ui.router.state.$state
  2998. *
  2999. * @description
  3000. * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
  3001. * but only checks for the full state name. If params is supplied then it will be
  3002. * tested for strict equality against the current active params object, so all params
  3003. * must match with none missing and no extras.
  3004. *
  3005. * @example
  3006. * <pre>
  3007. * $state.$current.name = 'contacts.details.item';
  3008. *
  3009. * // absolute name
  3010. * $state.is('contact.details.item'); // returns true
  3011. * $state.is(contactDetailItemStateObject); // returns true
  3012. *
  3013. * // relative name (. and ^), typically from a template
  3014. * // E.g. from the 'contacts.details' template
  3015. * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
  3016. * </pre>
  3017. *
  3018. * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
  3019. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
  3020. * to test against the current active state.
  3021. * @param {object=} options An options object. The options are:
  3022. *
  3023. * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
  3024. * test relative to `options.relative` state (or name).
  3025. *
  3026. * @returns {boolean} Returns true if it is the state.
  3027. */
  3028. $state.is = function is(stateOrName, params, options) {
  3029. options = extend({ relative: $state.$current }, options || {});
  3030. var state = findState(stateOrName, options.relative);
  3031. if (!isDefined(state)) { return undefined; }
  3032. if ($state.$current !== state) { return false; }
  3033. return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
  3034. };
  3035. /**
  3036. * @ngdoc function
  3037. * @name ui.router.state.$state#includes
  3038. * @methodOf ui.router.state.$state
  3039. *
  3040. * @description
  3041. * A method to determine if the current active state is equal to or is the child of the
  3042. * state stateName. If any params are passed then they will be tested for a match as well.
  3043. * Not all the parameters need to be passed, just the ones you'd like to test for equality.
  3044. *
  3045. * @example
  3046. * Partial and relative names
  3047. * <pre>
  3048. * $state.$current.name = 'contacts.details.item';
  3049. *
  3050. * // Using partial names
  3051. * $state.includes("contacts"); // returns true
  3052. * $state.includes("contacts.details"); // returns true
  3053. * $state.includes("contacts.details.item"); // returns true
  3054. * $state.includes("contacts.list"); // returns false
  3055. * $state.includes("about"); // returns false
  3056. *
  3057. * // Using relative names (. and ^), typically from a template
  3058. * // E.g. from the 'contacts.details' template
  3059. * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
  3060. * </pre>
  3061. *
  3062. * Basic globbing patterns
  3063. * <pre>
  3064. * $state.$current.name = 'contacts.details.item.url';
  3065. *
  3066. * $state.includes("*.details.*.*"); // returns true
  3067. * $state.includes("*.details.**"); // returns true
  3068. * $state.includes("**.item.**"); // returns true
  3069. * $state.includes("*.details.item.url"); // returns true
  3070. * $state.includes("*.details.*.url"); // returns true
  3071. * $state.includes("*.details.*"); // returns false
  3072. * $state.includes("item.**"); // returns false
  3073. * </pre>
  3074. *
  3075. * @param {string} stateOrName A partial name, relative name, or glob pattern
  3076. * to be searched for within the current state name.
  3077. * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
  3078. * that you'd like to test against the current active state.
  3079. * @param {object=} options An options object. The options are:
  3080. *
  3081. * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
  3082. * .includes will test relative to `options.relative` state (or name).
  3083. *
  3084. * @returns {boolean} Returns true if it does include the state
  3085. */
  3086. $state.includes = function includes(stateOrName, params, options) {
  3087. options = extend({ relative: $state.$current }, options || {});
  3088. if (isString(stateOrName) && isGlob(stateOrName)) {
  3089. if (!doesStateMatchGlob(stateOrName)) {
  3090. return false;
  3091. }
  3092. stateOrName = $state.$current.name;
  3093. }
  3094. var state = findState(stateOrName, options.relative);
  3095. if (!isDefined(state)) { return undefined; }
  3096. if (!isDefined($state.$current.includes[state.name])) { return false; }
  3097. return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
  3098. };
  3099. /**
  3100. * @ngdoc function
  3101. * @name ui.router.state.$state#href
  3102. * @methodOf ui.router.state.$state
  3103. *
  3104. * @description
  3105. * A url generation method that returns the compiled url for the given state populated with the given params.
  3106. *
  3107. * @example
  3108. * <pre>
  3109. * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
  3110. * </pre>
  3111. *
  3112. * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
  3113. * @param {object=} params An object of parameter values to fill the state's required parameters.
  3114. * @param {object=} options Options object. The options are:
  3115. *
  3116. * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
  3117. * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
  3118. * ancestor with a valid url).
  3119. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  3120. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  3121. * defines which state to be relative from.
  3122. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  3123. *
  3124. * @returns {string} compiled state url
  3125. */
  3126. $state.href = function href(stateOrName, params, options) {
  3127. options = extend({
  3128. lossy: true,
  3129. inherit: true,
  3130. absolute: false,
  3131. relative: $state.$current
  3132. }, options || {});
  3133. var state = findState(stateOrName, options.relative);
  3134. if (!isDefined(state)) return null;
  3135. if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
  3136. var nav = (state && options.lossy) ? state.navigable : state;
  3137. if (!nav || nav.url === undefined || nav.url === null) {
  3138. return null;
  3139. }
  3140. return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), {
  3141. absolute: options.absolute
  3142. });
  3143. };
  3144. /**
  3145. * @ngdoc function
  3146. * @name ui.router.state.$state#get
  3147. * @methodOf ui.router.state.$state
  3148. *
  3149. * @description
  3150. * Returns the state configuration object for any specific state or all states.
  3151. *
  3152. * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
  3153. * the requested state. If not provided, returns an array of ALL state configs.
  3154. * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
  3155. * @returns {Object|Array} State configuration object or array of all objects.
  3156. */
  3157. $state.get = function (stateOrName, context) {
  3158. if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
  3159. var state = findState(stateOrName, context || $state.$current);
  3160. return (state && state.self) ? state.self : null;
  3161. };
  3162. function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
  3163. // Make a restricted $stateParams with only the parameters that apply to this state if
  3164. // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
  3165. // we also need $stateParams to be available for any $injector calls we make during the
  3166. // dependency resolution process.
  3167. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
  3168. var locals = { $stateParams: $stateParams };
  3169. // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
  3170. // We're also including $stateParams in this; that way the parameters are restricted
  3171. // to the set that should be visible to the state, and are independent of when we update
  3172. // the global $state and $stateParams values.
  3173. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
  3174. var promises = [dst.resolve.then(function (globals) {
  3175. dst.globals = globals;
  3176. })];
  3177. if (inherited) promises.push(inherited);
  3178. // Resolve template and dependencies for all views.
  3179. forEach(state.views, function (view, name) {
  3180. var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
  3181. injectables.$template = [ function () {
  3182. return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: options.notify }) || '';
  3183. }];
  3184. promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
  3185. // References to the controller (only instantiated at link time)
  3186. if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
  3187. var injectLocals = angular.extend({}, injectables, locals);
  3188. result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
  3189. } else {
  3190. result.$$controller = view.controller;
  3191. }
  3192. // Provide access to the state itself for internal use
  3193. result.$$state = state;
  3194. result.$$controllerAs = view.controllerAs;
  3195. dst[name] = result;
  3196. }));
  3197. });
  3198. // Wait for all the promises and then return the activation object
  3199. return $q.all(promises).then(function (values) {
  3200. return dst;
  3201. });
  3202. }
  3203. return $state;
  3204. }
  3205. function shouldTriggerReload(to, from, locals, options) {
  3206. if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) {
  3207. return true;
  3208. }
  3209. }
  3210. }
  3211. angular.module('ui.router.state')
  3212. .value('$stateParams', {})
  3213. .provider('$state', $StateProvider);
  3214. $ViewProvider.$inject = [];
  3215. function $ViewProvider() {
  3216. this.$get = $get;
  3217. /**
  3218. * @ngdoc object
  3219. * @name ui.router.state.$view
  3220. *
  3221. * @requires ui.router.util.$templateFactory
  3222. * @requires $rootScope
  3223. *
  3224. * @description
  3225. *
  3226. */
  3227. $get.$inject = ['$rootScope', '$templateFactory'];
  3228. function $get( $rootScope, $templateFactory) {
  3229. return {
  3230. // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
  3231. /**
  3232. * @ngdoc function
  3233. * @name ui.router.state.$view#load
  3234. * @methodOf ui.router.state.$view
  3235. *
  3236. * @description
  3237. *
  3238. * @param {string} name name
  3239. * @param {object} options option object.
  3240. */
  3241. load: function load(name, options) {
  3242. var result, defaults = {
  3243. template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
  3244. };
  3245. options = extend(defaults, options);
  3246. if (options.view) {
  3247. result = $templateFactory.fromConfig(options.view, options.params, options.locals);
  3248. }
  3249. if (result && options.notify) {
  3250. /**
  3251. * @ngdoc event
  3252. * @name ui.router.state.$state#$viewContentLoading
  3253. * @eventOf ui.router.state.$view
  3254. * @eventType broadcast on root scope
  3255. * @description
  3256. *
  3257. * Fired once the view **begins loading**, *before* the DOM is rendered.
  3258. *
  3259. * @param {Object} event Event object.
  3260. * @param {Object} viewConfig The view config properties (template, controller, etc).
  3261. *
  3262. * @example
  3263. *
  3264. * <pre>
  3265. * $scope.$on('$viewContentLoading',
  3266. * function(event, viewConfig){
  3267. * // Access to all the view config properties.
  3268. * // and one special property 'targetView'
  3269. * // viewConfig.targetView
  3270. * });
  3271. * </pre>
  3272. */
  3273. $rootScope.$broadcast('$viewContentLoading', options);
  3274. }
  3275. return result;
  3276. }
  3277. };
  3278. }
  3279. }
  3280. angular.module('ui.router.state').provider('$view', $ViewProvider);
  3281. /**
  3282. * @ngdoc object
  3283. * @name ui.router.state.$uiViewScrollProvider
  3284. *
  3285. * @description
  3286. * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
  3287. */
  3288. function $ViewScrollProvider() {
  3289. var useAnchorScroll = false;
  3290. /**
  3291. * @ngdoc function
  3292. * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
  3293. * @methodOf ui.router.state.$uiViewScrollProvider
  3294. *
  3295. * @description
  3296. * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
  3297. * scrolling based on the url anchor.
  3298. */
  3299. this.useAnchorScroll = function () {
  3300. useAnchorScroll = true;
  3301. };
  3302. /**
  3303. * @ngdoc object
  3304. * @name ui.router.state.$uiViewScroll
  3305. *
  3306. * @requires $anchorScroll
  3307. * @requires $timeout
  3308. *
  3309. * @description
  3310. * When called with a jqLite element, it scrolls the element into view (after a
  3311. * `$timeout` so the DOM has time to refresh).
  3312. *
  3313. * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
  3314. * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
  3315. */
  3316. this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
  3317. if (useAnchorScroll) {
  3318. return $anchorScroll;
  3319. }
  3320. return function ($element) {
  3321. $timeout(function () {
  3322. $element[0].scrollIntoView();
  3323. }, 0, false);
  3324. };
  3325. }];
  3326. }
  3327. angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
  3328. /**
  3329. * @ngdoc directive
  3330. * @name ui.router.state.directive:ui-view
  3331. *
  3332. * @requires ui.router.state.$state
  3333. * @requires $compile
  3334. * @requires $controller
  3335. * @requires $injector
  3336. * @requires ui.router.state.$uiViewScroll
  3337. * @requires $document
  3338. *
  3339. * @restrict ECA
  3340. *
  3341. * @description
  3342. * The ui-view directive tells $state where to place your templates.
  3343. *
  3344. * @param {string=} name A view name. The name should be unique amongst the other views in the
  3345. * same state. You can have views of the same name that live in different states.
  3346. *
  3347. * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
  3348. * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
  3349. * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
  3350. * scroll ui-view elements into view when they are populated during a state activation.
  3351. *
  3352. * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
  3353. * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
  3354. *
  3355. * @param {string=} onload Expression to evaluate whenever the view updates.
  3356. *
  3357. * @example
  3358. * A view can be unnamed or named.
  3359. * <pre>
  3360. * <!-- Unnamed -->
  3361. * <div ui-view></div>
  3362. *
  3363. * <!-- Named -->
  3364. * <div ui-view="viewName"></div>
  3365. * </pre>
  3366. *
  3367. * You can only have one unnamed view within any template (or root html). If you are only using a
  3368. * single view and it is unnamed then you can populate it like so:
  3369. * <pre>
  3370. * <div ui-view></div>
  3371. * $stateProvider.state("home", {
  3372. * template: "<h1>HELLO!</h1>"
  3373. * })
  3374. * </pre>
  3375. *
  3376. * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
  3377. * config property, by name, in this case an empty name:
  3378. * <pre>
  3379. * $stateProvider.state("home", {
  3380. * views: {
  3381. * "": {
  3382. * template: "<h1>HELLO!</h1>"
  3383. * }
  3384. * }
  3385. * })
  3386. * </pre>
  3387. *
  3388. * But typically you'll only use the views property if you name your view or have more than one view
  3389. * in the same template. There's not really a compelling reason to name a view if its the only one,
  3390. * but you could if you wanted, like so:
  3391. * <pre>
  3392. * <div ui-view="main"></div>
  3393. * </pre>
  3394. * <pre>
  3395. * $stateProvider.state("home", {
  3396. * views: {
  3397. * "main": {
  3398. * template: "<h1>HELLO!</h1>"
  3399. * }
  3400. * }
  3401. * })
  3402. * </pre>
  3403. *
  3404. * Really though, you'll use views to set up multiple views:
  3405. * <pre>
  3406. * <div ui-view></div>
  3407. * <div ui-view="chart"></div>
  3408. * <div ui-view="data"></div>
  3409. * </pre>
  3410. *
  3411. * <pre>
  3412. * $stateProvider.state("home", {
  3413. * views: {
  3414. * "": {
  3415. * template: "<h1>HELLO!</h1>"
  3416. * },
  3417. * "chart": {
  3418. * template: "<chart_thing/>"
  3419. * },
  3420. * "data": {
  3421. * template: "<data_thing/>"
  3422. * }
  3423. * }
  3424. * })
  3425. * </pre>
  3426. *
  3427. * Examples for `autoscroll`:
  3428. *
  3429. * <pre>
  3430. * <!-- If autoscroll present with no expression,
  3431. * then scroll ui-view into view -->
  3432. * <ui-view autoscroll/>
  3433. *
  3434. * <!-- If autoscroll present with valid expression,
  3435. * then scroll ui-view into view if expression evaluates to true -->
  3436. * <ui-view autoscroll='true'/>
  3437. * <ui-view autoscroll='false'/>
  3438. * <ui-view autoscroll='scopeVariable'/>
  3439. * </pre>
  3440. */
  3441. $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
  3442. function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
  3443. function getService() {
  3444. return ($injector.has) ? function(service) {
  3445. return $injector.has(service) ? $injector.get(service) : null;
  3446. } : function(service) {
  3447. try {
  3448. return $injector.get(service);
  3449. } catch (e) {
  3450. return null;
  3451. }
  3452. };
  3453. }
  3454. var service = getService(),
  3455. $animator = service('$animator'),
  3456. $animate = service('$animate');
  3457. // Returns a set of DOM manipulation functions based on which Angular version
  3458. // it should use
  3459. function getRenderer(attrs, scope) {
  3460. var statics = function() {
  3461. return {
  3462. enter: function (element, target, cb) { target.after(element); cb(); },
  3463. leave: function (element, cb) { element.remove(); cb(); }
  3464. };
  3465. };
  3466. if ($animate) {
  3467. return {
  3468. enter: function(element, target, cb) {
  3469. var promise = $animate.enter(element, null, target, cb);
  3470. if (promise && promise.then) promise.then(cb);
  3471. },
  3472. leave: function(element, cb) {
  3473. var promise = $animate.leave(element, cb);
  3474. if (promise && promise.then) promise.then(cb);
  3475. }
  3476. };
  3477. }
  3478. if ($animator) {
  3479. var animate = $animator && $animator(scope, attrs);
  3480. return {
  3481. enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
  3482. leave: function(element, cb) { animate.leave(element); cb(); }
  3483. };
  3484. }
  3485. return statics();
  3486. }
  3487. var directive = {
  3488. restrict: 'ECA',
  3489. terminal: true,
  3490. priority: 400,
  3491. transclude: 'element',
  3492. compile: function (tElement, tAttrs, $transclude) {
  3493. return function (scope, $element, attrs) {
  3494. var previousEl, currentEl, currentScope, latestLocals,
  3495. onloadExp = attrs.onload || '',
  3496. autoScrollExp = attrs.autoscroll,
  3497. renderer = getRenderer(attrs, scope);
  3498. scope.$on('$stateChangeSuccess', function() {
  3499. updateView(false);
  3500. });
  3501. scope.$on('$viewContentLoading', function() {
  3502. updateView(false);
  3503. });
  3504. updateView(true);
  3505. function cleanupLastView() {
  3506. if (previousEl) {
  3507. previousEl.remove();
  3508. previousEl = null;
  3509. }
  3510. if (currentScope) {
  3511. currentScope.$destroy();
  3512. currentScope = null;
  3513. }
  3514. if (currentEl) {
  3515. renderer.leave(currentEl, function() {
  3516. previousEl = null;
  3517. });
  3518. previousEl = currentEl;
  3519. currentEl = null;
  3520. }
  3521. }
  3522. function updateView(firstTime) {
  3523. var newScope,
  3524. name = getUiViewName(scope, attrs, $element, $interpolate),
  3525. previousLocals = name && $state.$current && $state.$current.locals[name];
  3526. if (!firstTime && previousLocals === latestLocals) return; // nothing to do
  3527. newScope = scope.$new();
  3528. latestLocals = $state.$current.locals[name];
  3529. var clone = $transclude(newScope, function(clone) {
  3530. renderer.enter(clone, $element, function onUiViewEnter() {
  3531. if(currentScope) {
  3532. currentScope.$emit('$viewContentAnimationEnded');
  3533. }
  3534. if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
  3535. $uiViewScroll(clone);
  3536. }
  3537. });
  3538. cleanupLastView();
  3539. });
  3540. currentEl = clone;
  3541. currentScope = newScope;
  3542. /**
  3543. * @ngdoc event
  3544. * @name ui.router.state.directive:ui-view#$viewContentLoaded
  3545. * @eventOf ui.router.state.directive:ui-view
  3546. * @eventType emits on ui-view directive scope
  3547. * @description *
  3548. * Fired once the view is **loaded**, *after* the DOM is rendered.
  3549. *
  3550. * @param {Object} event Event object.
  3551. */
  3552. currentScope.$emit('$viewContentLoaded');
  3553. currentScope.$eval(onloadExp);
  3554. }
  3555. };
  3556. }
  3557. };
  3558. return directive;
  3559. }
  3560. $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
  3561. function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
  3562. return {
  3563. restrict: 'ECA',
  3564. priority: -400,
  3565. compile: function (tElement) {
  3566. var initial = tElement.html();
  3567. return function (scope, $element, attrs) {
  3568. var current = $state.$current,
  3569. name = getUiViewName(scope, attrs, $element, $interpolate),
  3570. locals = current && current.locals[name];
  3571. if (! locals) {
  3572. return;
  3573. }
  3574. $element.data('$uiView', { name: name, state: locals.$$state });
  3575. $element.html(locals.$template ? locals.$template : initial);
  3576. var link = $compile($element.contents());
  3577. if (locals.$$controller) {
  3578. locals.$scope = scope;
  3579. var controller = $controller(locals.$$controller, locals);
  3580. if (locals.$$controllerAs) {
  3581. scope[locals.$$controllerAs] = controller;
  3582. }
  3583. $element.data('$ngControllerController', controller);
  3584. $element.children().data('$ngControllerController', controller);
  3585. }
  3586. link(scope);
  3587. };
  3588. }
  3589. };
  3590. }
  3591. /**
  3592. * Shared ui-view code for both directives:
  3593. * Given scope, element, and its attributes, return the view's name
  3594. */
  3595. function getUiViewName(scope, attrs, element, $interpolate) {
  3596. var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
  3597. var inherited = element.inheritedData('$uiView');
  3598. return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
  3599. }
  3600. angular.module('ui.router.state').directive('uiView', $ViewDirective);
  3601. angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
  3602. function parseStateRef(ref, current) {
  3603. var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
  3604. if (preparsed) ref = current + '(' + preparsed[1] + ')';
  3605. parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
  3606. if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
  3607. return { state: parsed[1], paramExpr: parsed[3] || null };
  3608. }
  3609. function stateContext(el) {
  3610. var stateData = el.parent().inheritedData('$uiView');
  3611. if (stateData && stateData.state && stateData.state.name) {
  3612. return stateData.state;
  3613. }
  3614. }
  3615. /**
  3616. * @ngdoc directive
  3617. * @name ui.router.state.directive:ui-sref
  3618. *
  3619. * @requires ui.router.state.$state
  3620. * @requires $timeout
  3621. *
  3622. * @restrict A
  3623. *
  3624. * @description
  3625. * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
  3626. * URL, the directive will automatically generate & update the `href` attribute via
  3627. * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
  3628. * the link will trigger a state transition with optional parameters.
  3629. *
  3630. * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
  3631. * handled natively by the browser.
  3632. *
  3633. * You can also use relative state paths within ui-sref, just like the relative
  3634. * paths passed to `$state.go()`. You just need to be aware that the path is relative
  3635. * to the state that the link lives in, in other words the state that loaded the
  3636. * template containing the link.
  3637. *
  3638. * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
  3639. * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
  3640. * and `reload`.
  3641. *
  3642. * @example
  3643. * Here's an example of how you'd use ui-sref and how it would compile. If you have the
  3644. * following template:
  3645. * <pre>
  3646. * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
  3647. *
  3648. * <ul>
  3649. * <li ng-repeat="contact in contacts">
  3650. * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
  3651. * </li>
  3652. * </ul>
  3653. * </pre>
  3654. *
  3655. * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
  3656. * <pre>
  3657. * <a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a> | <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
  3658. *
  3659. * <ul>
  3660. * <li ng-repeat="contact in contacts">
  3661. * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
  3662. * </li>
  3663. * <li ng-repeat="contact in contacts">
  3664. * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
  3665. * </li>
  3666. * <li ng-repeat="contact in contacts">
  3667. * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
  3668. * </li>
  3669. * </ul>
  3670. *
  3671. * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
  3672. * </pre>
  3673. *
  3674. * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
  3675. * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
  3676. */
  3677. $StateRefDirective.$inject = ['$state', '$timeout'];
  3678. function $StateRefDirective($state, $timeout) {
  3679. var allowedOptions = ['location', 'inherit', 'reload'];
  3680. return {
  3681. restrict: 'A',
  3682. require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
  3683. link: function(scope, element, attrs, uiSrefActive) {
  3684. var ref = parseStateRef(attrs.uiSref, $state.current.name);
  3685. var params = null, url = null, base = stateContext(element) || $state.$current;
  3686. var newHref = null, isAnchor = element.prop("tagName") === "A";
  3687. var isForm = element[0].nodeName === "FORM";
  3688. var attr = isForm ? "action" : "href", nav = true;
  3689. var options = { relative: base, inherit: true };
  3690. var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
  3691. angular.forEach(allowedOptions, function(option) {
  3692. if (option in optionsOverride) {
  3693. options[option] = optionsOverride[option];
  3694. }
  3695. });
  3696. var update = function(newVal) {
  3697. if (newVal) params = angular.copy(newVal);
  3698. if (!nav) return;
  3699. newHref = $state.href(ref.state, params, options);
  3700. var activeDirective = uiSrefActive[1] || uiSrefActive[0];
  3701. if (activeDirective) {
  3702. activeDirective.$$setStateInfo(ref.state, params);
  3703. }
  3704. if (newHref === null) {
  3705. nav = false;
  3706. return false;
  3707. }
  3708. attrs.$set(attr, newHref);
  3709. };
  3710. if (ref.paramExpr) {
  3711. scope.$watch(ref.paramExpr, function(newVal, oldVal) {
  3712. if (newVal !== params) update(newVal);
  3713. }, true);
  3714. params = angular.copy(scope.$eval(ref.paramExpr));
  3715. }
  3716. update();
  3717. if (isForm) return;
  3718. element.bind("click", function(e) {
  3719. var button = e.which || e.button;
  3720. if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
  3721. // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
  3722. var transition = $timeout(function() {
  3723. $state.go(ref.state, params, options);
  3724. });
  3725. e.preventDefault();
  3726. // if the state has no URL, ignore one preventDefault from the <a> directive.
  3727. var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
  3728. e.preventDefault = function() {
  3729. if (ignorePreventDefaultCount-- <= 0)
  3730. $timeout.cancel(transition);
  3731. };
  3732. }
  3733. });
  3734. }
  3735. };
  3736. }
  3737. /**
  3738. * @ngdoc directive
  3739. * @name ui.router.state.directive:ui-sref-active
  3740. *
  3741. * @requires ui.router.state.$state
  3742. * @requires ui.router.state.$stateParams
  3743. * @requires $interpolate
  3744. *
  3745. * @restrict A
  3746. *
  3747. * @description
  3748. * A directive working alongside ui-sref to add classes to an element when the
  3749. * related ui-sref directive's state is active, and removing them when it is inactive.
  3750. * The primary use-case is to simplify the special appearance of navigation menus
  3751. * relying on `ui-sref`, by having the "active" state's menu button appear different,
  3752. * distinguishing it from the inactive menu items.
  3753. *
  3754. * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
  3755. * ui-sref-active found at the same level or above the ui-sref will be used.
  3756. *
  3757. * Will activate when the ui-sref's target state or any child state is active. If you
  3758. * need to activate only when the ui-sref target state is active and *not* any of
  3759. * it's children, then you will use
  3760. * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
  3761. *
  3762. * @example
  3763. * Given the following template:
  3764. * <pre>
  3765. * <ul>
  3766. * <li ui-sref-active="active" class="item">
  3767. * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  3768. * </li>
  3769. * </ul>
  3770. * </pre>
  3771. *
  3772. *
  3773. * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
  3774. * the resulting HTML will appear as (note the 'active' class):
  3775. * <pre>
  3776. * <ul>
  3777. * <li ui-sref-active="active" class="item active">
  3778. * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
  3779. * </li>
  3780. * </ul>
  3781. * </pre>
  3782. *
  3783. * The class name is interpolated **once** during the directives link time (any further changes to the
  3784. * interpolated value are ignored).
  3785. *
  3786. * Multiple classes may be specified in a space-separated format:
  3787. * <pre>
  3788. * <ul>
  3789. * <li ui-sref-active='class1 class2 class3'>
  3790. * <a ui-sref="app.user">link</a>
  3791. * </li>
  3792. * </ul>
  3793. * </pre>
  3794. */
  3795. /**
  3796. * @ngdoc directive
  3797. * @name ui.router.state.directive:ui-sref-active-eq
  3798. *
  3799. * @requires ui.router.state.$state
  3800. * @requires ui.router.state.$stateParams
  3801. * @requires $interpolate
  3802. *
  3803. * @restrict A
  3804. *
  3805. * @description
  3806. * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
  3807. * when the exact target state used in the `ui-sref` is active; no child states.
  3808. *
  3809. */
  3810. $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
  3811. function $StateRefActiveDirective($state, $stateParams, $interpolate) {
  3812. return {
  3813. restrict: "A",
  3814. controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
  3815. var state, params, activeClass;
  3816. // There probably isn't much point in $observing this
  3817. // uiSrefActive and uiSrefActiveEq share the same directive object with some
  3818. // slight difference in logic routing
  3819. activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
  3820. // Allow uiSref to communicate with uiSrefActive[Equals]
  3821. this.$$setStateInfo = function (newState, newParams) {
  3822. state = $state.get(newState, stateContext($element));
  3823. params = newParams;
  3824. update();
  3825. };
  3826. $scope.$on('$stateChangeSuccess', update);
  3827. // Update route state
  3828. function update() {
  3829. if (isMatch()) {
  3830. $element.addClass(activeClass);
  3831. } else {
  3832. $element.removeClass(activeClass);
  3833. }
  3834. }
  3835. function isMatch() {
  3836. if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
  3837. return state && $state.is(state.name, params);
  3838. } else {
  3839. return state && $state.includes(state.name, params);
  3840. }
  3841. }
  3842. }]
  3843. };
  3844. }
  3845. angular.module('ui.router.state')
  3846. .directive('uiSref', $StateRefDirective)
  3847. .directive('uiSrefActive', $StateRefActiveDirective)
  3848. .directive('uiSrefActiveEq', $StateRefActiveDirective);
  3849. /**
  3850. * @ngdoc filter
  3851. * @name ui.router.state.filter:isState
  3852. *
  3853. * @requires ui.router.state.$state
  3854. *
  3855. * @description
  3856. * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
  3857. */
  3858. $IsStateFilter.$inject = ['$state'];
  3859. function $IsStateFilter($state) {
  3860. var isFilter = function (state) {
  3861. return $state.is(state);
  3862. };
  3863. isFilter.$stateful = true;
  3864. return isFilter;
  3865. }
  3866. /**
  3867. * @ngdoc filter
  3868. * @name ui.router.state.filter:includedByState
  3869. *
  3870. * @requires ui.router.state.$state
  3871. *
  3872. * @description
  3873. * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
  3874. */
  3875. $IncludedByStateFilter.$inject = ['$state'];
  3876. function $IncludedByStateFilter($state) {
  3877. var includesFilter = function (state) {
  3878. return $state.includes(state);
  3879. };
  3880. includesFilter.$stateful = true;
  3881. return includesFilter;
  3882. }
  3883. angular.module('ui.router.state')
  3884. .filter('isState', $IsStateFilter)
  3885. .filter('includedByState', $IncludedByStateFilter);
  3886. })(window, window.angular);