2 * State-based routing for AngularJS
4 * @link http://angular-ui.github.com/
5 * @license MIT License, http://www.opensource.org/licenses/MIT
8 /* commonjs package manager support (eg componentjs) */
9 if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
10 module.exports = 'ui.router';
13 (function (window, angular, undefined) {
14 /*jshint globalstrict:true*/
15 /*global angular:false*/
18 var isDefined = angular.isDefined,
19 isFunction = angular.isFunction,
20 isString = angular.isString,
21 isObject = angular.isObject,
22 isArray = angular.isArray,
23 forEach = angular.forEach,
24 extend = angular.extend,
26 toJson = angular.toJson;
28 function inherit(parent, extra) {
29 return extend(new (extend(function() {}, { prototype: parent }))(), extra);
33 forEach(arguments, function(obj) {
35 forEach(obj, function(value, key) {
36 if (!dst.hasOwnProperty(key)) dst[key] = value;
44 * Finds the common ancestor path between two states.
46 * @param {Object} first The first state.
47 * @param {Object} second The second state.
48 * @return {Array} Returns an array of state names in descending order, not including the root.
50 function ancestors(first, second) {
53 for (var n in first.path) {
54 if (first.path[n] !== second.path[n]) break;
55 path.push(first.path[n]);
61 * IE8-safe wrapper for `Object.keys()`.
63 * @param {Object} object A JavaScript object.
64 * @return {Array} Returns the keys of the object as an array.
66 function objectKeys(object) {
68 return Object.keys(object);
72 forEach(object, function(val, key) {
79 * IE8-safe wrapper for `Array.prototype.indexOf()`.
81 * @param {Array} array A JavaScript array.
82 * @param {*} value A value to search the array for.
83 * @return {Number} Returns the array index value of `value`, or `-1` if not present.
85 function indexOf(array, value) {
86 if (Array.prototype.indexOf) {
87 return array.indexOf(value, Number(arguments[2]) || 0);
89 var len = array.length >>> 0, from = Number(arguments[2]) || 0;
90 from = (from < 0) ? Math.ceil(from) : Math.floor(from);
92 if (from < 0) from += len;
94 for (; from < len; from++) {
95 if (from in array && array[from] === value) return from;
101 * Merges a set of parameters with all parameters inherited between the common parents of the
102 * current state and a given destination state.
104 * @param {Object} currentParams The value of the current state parameters ($stateParams).
105 * @param {Object} newParams The set of parameters which will be composited with inherited params.
106 * @param {Object} $current Internal definition of object representing the current state.
107 * @param {Object} $to Internal definition of object representing state to transition to.
109 function inheritParams(currentParams, newParams, $current, $to) {
110 var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
112 for (var i in parents) {
113 if (!parents[i] || !parents[i].params) continue;
114 parentParams = objectKeys(parents[i].params);
115 if (!parentParams.length) continue;
117 for (var j in parentParams) {
118 if (indexOf(inheritList, parentParams[j]) >= 0) continue;
119 inheritList.push(parentParams[j]);
120 inherited[parentParams[j]] = currentParams[parentParams[j]];
123 return extend({}, inherited, newParams);
127 * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
129 * @param {Object} a The first object.
130 * @param {Object} b The second object.
131 * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
132 * it defaults to the list of keys in `a`.
133 * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
135 function equalForKeys(a, b, keys) {
138 for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
141 for (var i=0; i<keys.length; i++) {
143 if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
149 * Returns the subset of an object, based on a list of keys.
151 * @param {Array} keys
152 * @param {Object} values
153 * @return {Boolean} Returns a subset of `values`.
155 function filterByKeys(keys, values) {
158 forEach(keys, function (name) {
159 filtered[name] = values[name];
165 // when you know that your index values will be unique, or you want last-one-in to win
166 function indexBy(array, propName) {
168 forEach(array, function(item) {
169 result[item[propName]] = item;
174 // extracted from underscore.js
175 // Return a copy of the object only containing the whitelisted properties.
178 var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
179 forEach(keys, function(key) {
180 if (key in obj) copy[key] = obj[key];
185 // extracted from underscore.js
186 // Return a copy of the object omitting the blacklisted properties.
189 var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
190 for (var key in obj) {
191 if (indexOf(keys, key) == -1) copy[key] = obj[key];
196 function pluck(collection, key) {
197 var result = isArray(collection) ? [] : {};
199 forEach(collection, function(val, i) {
200 result[i] = isFunction(key) ? key(val) : val[key];
205 function filter(collection, callback) {
206 var array = isArray(collection);
207 var result = array ? [] : {};
208 forEach(collection, function(val, i) {
209 if (callback(val, i)) {
210 result[array ? result.length : i] = val;
216 function map(collection, callback) {
217 var result = isArray(collection) ? [] : {};
219 forEach(collection, function(val, i) {
220 result[i] = callback(val, i);
227 * @name ui.router.util
230 * # ui.router.util sub-module
232 * This module is a dependency of other sub-modules. Do not include this module as a dependency
233 * in your angular app (use {@link ui.router} module instead).
236 angular.module('ui.router.util', ['ng']);
240 * @name ui.router.router
242 * @requires ui.router.util
245 * # ui.router.router sub-module
247 * This module is a dependency of other sub-modules. Do not include this module as a dependency
248 * in your angular app (use {@link ui.router} module instead).
250 angular.module('ui.router.router', ['ui.router.util']);
254 * @name ui.router.state
256 * @requires ui.router.router
257 * @requires ui.router.util
260 * # ui.router.state sub-module
262 * This module is a dependency of the main ui.router module. Do not include this module as a dependency
263 * in your angular app (use {@link ui.router} module instead).
266 angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
272 * @requires ui.router.state
277 * ## The main module for ui.router
278 * There are several sub-modules included with the ui.router module, however only this module is needed
279 * as a dependency within your angular app. The other modules are for organization purposes.
282 * * ui.router - the main "umbrella" module
283 * * ui.router.router -
285 * *You'll need to include **only** this module as the dependency within your angular app.*
289 * <html ng-app="myApp">
291 * <script src="js/angular.js"></script>
292 * <!-- Include the ui-router script -->
293 * <script src="js/angular-ui-router.min.js"></script>
295 * // ...and add 'ui.router' as a dependency
296 * var myApp = angular.module('myApp', ['ui.router']);
304 angular.module('ui.router', ['ui.router.state']);
306 angular.module('ui.router.compat', ['ui.router']);
310 * @name ui.router.util.$resolve
313 * @requires $injector
316 * Manages resolution of (acyclic) graphs of promises.
318 $Resolve.$inject = ['$q', '$injector'];
319 function $Resolve( $q, $injector) {
321 var VISIT_IN_PROGRESS = 1,
324 NO_DEPENDENCIES = [],
326 NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
331 * @name ui.router.util.$resolve#study
332 * @methodOf ui.router.util.$resolve
335 * Studies a set of invocables that are likely to be used multiple times.
337 * $resolve.study(invocables)(locals, parent, self)
341 * $resolve.resolve(invocables, locals, parent, self)
343 * but the former is more efficient (in fact `resolve` just calls `study`
346 * @param {object} invocables Invocable objects
347 * @return {function} a function to pass in locals, parent and self
349 this.study = function (invocables) {
350 if (!isObject(invocables)) throw new Error("'invocables' must be an object");
351 var invocableKeys = objectKeys(invocables || {});
353 // Perform a topological sort of invocables to build an ordered plan
354 var plan = [], cycle = [], visited = {};
355 function visit(value, key) {
356 if (visited[key] === VISIT_DONE) return;
359 if (visited[key] === VISIT_IN_PROGRESS) {
360 cycle.splice(0, indexOf(cycle, key));
361 throw new Error("Cyclic dependency: " + cycle.join(" -> "));
363 visited[key] = VISIT_IN_PROGRESS;
365 if (isString(value)) {
366 plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
368 var params = $injector.annotate(value);
369 forEach(params, function (param) {
370 if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
372 plan.push(key, value, params);
376 visited[key] = VISIT_DONE;
378 forEach(invocables, visit);
379 invocables = cycle = visited = null; // plan is all that's required
381 function isResolve(value) {
382 return isObject(value) && value.then && value.$$promises;
385 return function (locals, parent, self) {
386 if (isResolve(locals) && self === undefined) {
387 self = parent; parent = locals; locals = null;
389 if (!locals) locals = NO_LOCALS;
390 else if (!isObject(locals)) {
391 throw new Error("'locals' must be an object");
393 if (!parent) parent = NO_PARENT;
394 else if (!isResolve(parent)) {
395 throw new Error("'parent' must be a promise returned by $resolve.resolve()");
398 // To complete the overall resolution, we have to wait for the parent
399 // promise and for the promise for each invokable in our plan.
400 var resolution = $q.defer(),
401 result = resolution.promise,
402 promises = result.$$promises = {},
403 values = extend({}, locals),
404 wait = 1 + plan.length/3,
408 // Merge parent values we haven't got yet and publish our own $$values
410 if (!merged) merge(values, parent.$$values);
411 result.$$values = values;
412 result.$$promises = result.$$promises || true; // keep for isResolve()
413 delete result.$$inheritedValues;
414 resolution.resolve(values);
418 function fail(reason) {
419 result.$$failure = reason;
420 resolution.reject(reason);
423 // Short-circuit if parent has already failed
424 if (isDefined(parent.$$failure)) {
425 fail(parent.$$failure);
429 if (parent.$$inheritedValues) {
430 merge(values, omit(parent.$$inheritedValues, invocableKeys));
433 // Merge parent values if the parent has already resolved, or merge
434 // parent promises and wait if the parent resolve is still in progress.
435 extend(promises, parent.$$promises);
436 if (parent.$$values) {
437 merged = merge(values, omit(parent.$$values, invocableKeys));
438 result.$$inheritedValues = omit(parent.$$values, invocableKeys);
441 if (parent.$$inheritedValues) {
442 result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
444 parent.then(done, fail);
447 // Process each invocable in the plan, but ignore any where a local of the same name exists.
448 for (var i=0, ii=plan.length; i<ii; i+=3) {
449 if (locals.hasOwnProperty(plan[i])) done();
450 else invoke(plan[i], plan[i+1], plan[i+2]);
453 function invoke(key, invocable, params) {
454 // Create a deferred for this invocation. Failures will propagate to the resolution as well.
455 var invocation = $q.defer(), waitParams = 0;
456 function onfailure(reason) {
457 invocation.reject(reason);
460 // Wait for any parameter that we have a promise for (either from parent or from this
461 // resolve; in that case study() will have made sure it's ordered before us in the plan).
462 forEach(params, function (dep) {
463 if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
465 promises[dep].then(function (result) {
466 values[dep] = result;
467 if (!(--waitParams)) proceed();
471 if (!waitParams) proceed();
473 if (isDefined(result.$$failure)) return;
475 invocation.resolve($injector.invoke(invocable, self, values));
476 invocation.promise.then(function (result) {
477 values[key] = result;
484 // Publish promise synchronously; invocations further down in the plan may depend on it.
485 promises[key] = invocation.promise;
494 * @name ui.router.util.$resolve#resolve
495 * @methodOf ui.router.util.$resolve
498 * Resolves a set of invocables. An invocable is a function to be invoked via
499 * `$injector.invoke()`, and can have an arbitrary number of dependencies.
500 * An invocable can either return a value directly,
501 * or a `$q` promise. If a promise is returned it will be resolved and the
502 * resulting value will be used instead. Dependencies of invocables are resolved
503 * (in this order of precedence)
505 * - from the specified `locals`
506 * - from another invocable that is part of this `$resolve` call
507 * - from an invocable that is inherited from a `parent` call to `$resolve`
509 * - from any ancestor `$resolve` of that parent).
511 * The return value of `$resolve` is a promise for an object that contains
512 * (in this order of precedence)
514 * - any `locals` (if specified)
515 * - the resolved return values of all injectables
516 * - any values inherited from a `parent` call to `$resolve` (if specified)
518 * The promise will resolve after the `parent` promise (if any) and all promises
519 * returned by injectables have been resolved. If any invocable
520 * (or `$injector.invoke`) throws an exception, or if a promise returned by an
521 * invocable is rejected, the `$resolve` promise is immediately rejected with the
522 * same error. A rejection of a `parent` promise (if specified) will likewise be
523 * propagated immediately. Once the `$resolve` promise has been rejected, no
524 * further invocables will be called.
526 * Cyclic dependencies between invocables are not permitted and will caues `$resolve`
527 * to throw an error. As a special case, an injectable can depend on a parameter
528 * with the same name as the injectable, which will be fulfilled from the `parent`
529 * injectable of the same name. This allows inherited values to be decorated.
530 * Note that in this case any other injectable in the same `$resolve` with the same
531 * dependency would see the decorated value, not the inherited value.
533 * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
534 * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
537 * Invocables are invoked eagerly as soon as all dependencies are available.
538 * This is true even for dependencies inherited from a `parent` call to `$resolve`.
540 * As a special case, an invocable can be a string, in which case it is taken to
541 * be a service name to be passed to `$injector.get()`. This is supported primarily
542 * for backwards-compatibility with the `resolve` property of `$routeProvider`
545 * @param {object} invocables functions to invoke or
546 * `$injector` services to fetch.
547 * @param {object} locals values to make available to the injectables
548 * @param {object} parent a promise returned by another call to `$resolve`.
549 * @param {object} self the `this` for the invoked methods
550 * @return {object} Promise for an object that contains the resolved return value
551 * of all invocables, as well as any inherited and local values.
553 this.resolve = function (invocables, locals, parent, self) {
554 return this.study(invocables)(locals, parent, self);
558 angular.module('ui.router.util').service('$resolve', $Resolve);
563 * @name ui.router.util.$templateFactory
566 * @requires $templateCache
567 * @requires $injector
570 * Service. Manages loading of templates.
572 $TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
573 function $TemplateFactory( $http, $templateCache, $injector) {
577 * @name ui.router.util.$templateFactory#fromConfig
578 * @methodOf ui.router.util.$templateFactory
581 * Creates a template from a configuration object.
583 * @param {object} config Configuration object for which to load a template.
584 * The following properties are search in the specified order, and the first one
585 * that is defined is used to create the template:
587 * @param {string|object} config.template html string template or function to
588 * load via {@link ui.router.util.$templateFactory#fromString fromString}.
589 * @param {string|object} config.templateUrl url to load or a function returning
590 * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
591 * @param {Function} config.templateProvider function to invoke via
592 * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
593 * @param {object} params Parameters to pass to the template function.
594 * @param {object} locals Locals to pass to `invoke` if the template is loaded
595 * via a `templateProvider`. Defaults to `{ params: params }`.
597 * @return {string|object} The template html as a string, or a promise for
598 * that string,or `null` if no template is configured.
600 this.fromConfig = function (config, params, locals) {
602 isDefined(config.template) ? this.fromString(config.template, params) :
603 isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
604 isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
611 * @name ui.router.util.$templateFactory#fromString
612 * @methodOf ui.router.util.$templateFactory
615 * Creates a template from a string or a function returning a string.
617 * @param {string|object} template html template as a string or function that
618 * returns an html template as a string.
619 * @param {object} params Parameters to pass to the template function.
621 * @return {string|object} The template html as a string, or a promise for that
624 this.fromString = function (template, params) {
625 return isFunction(template) ? template(params) : template;
630 * @name ui.router.util.$templateFactory#fromUrl
631 * @methodOf ui.router.util.$templateFactory
634 * Loads a template from the a URL via `$http` and `$templateCache`.
636 * @param {string|Function} url url of the template to load, or a function
637 * that returns a url.
638 * @param {Object} params Parameters to pass to the url function.
639 * @return {string|Promise.<string>} The template html as a string, or a promise
642 this.fromUrl = function (url, params) {
643 if (isFunction(url)) url = url(params);
644 if (url == null) return null;
646 .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
647 .then(function(response) { return response.data; });
652 * @name ui.router.util.$templateFactory#fromProvider
653 * @methodOf ui.router.util.$templateFactory
656 * Creates a template by invoking an injectable provider function.
658 * @param {Function} provider Function to invoke via `$injector.invoke`
659 * @param {Object} params Parameters for the template.
660 * @param {Object} locals Locals to pass to `invoke`. Defaults to
661 * `{ params: params }`.
662 * @return {string|Promise.<string>} The template html as a string, or a promise
665 this.fromProvider = function (provider, params, locals) {
666 return $injector.invoke(provider, null, locals || { params: params });
670 angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
672 var $$UMFP; // reference to $UrlMatcherFactoryProvider
676 * @name ui.router.util.type:UrlMatcher
679 * Matches URLs against patterns and extracts named parameters from the path or the search
680 * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
681 * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
682 * do not influence whether or not a URL is matched, but their values are passed through into
683 * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
685 * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
686 * syntax, which optionally allows a regular expression for the parameter to be specified:
688 * * `':'` name - colon placeholder
689 * * `'*'` name - catch-all placeholder
690 * * `'{' name '}'` - curly placeholder
691 * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
692 * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
694 * Parameter names may contain only word characters (latin letters, digits, and underscore) and
695 * must be unique within the pattern (across both path and search parameters). For colon
696 * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
697 * number of characters other than '/'. For catch-all placeholders the path parameter matches
698 * any number of characters.
702 * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
703 * trailing slashes, and patterns have to match the entire path, not just a prefix.
704 * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
705 * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
706 * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
707 * * `'/user/{id:[^/]*}'` - Same as the previous example.
708 * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
709 * parameter consists of 1 to 8 hex digits.
710 * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
711 * path into the parameter 'path'.
712 * * `'/files/*path'` - ditto.
713 * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
714 * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
716 * @param {string} pattern The pattern to compile into a matcher.
717 * @param {Object} config A configuration object hash:
718 * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
719 * an existing UrlMatcher
721 * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
722 * * `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`.
724 * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
725 * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
726 * non-null) will start with this prefix.
728 * @property {string} source The pattern that was passed into the constructor
730 * @property {string} sourcePath The path portion of the source property
732 * @property {string} sourceSearch The search portion of the source property
734 * @property {string} regex The constructed regex that will be used to match against the url when
735 * it is time to determine which url will match.
737 * @returns {Object} New `UrlMatcher` object
739 function UrlMatcher(pattern, config, parentMatcher) {
740 config = extend({ params: {} }, isObject(config) ? config : {});
742 // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
746 // '{' name ':' regexp '}'
747 // The regular expression is somewhat complicated due to the need to allow curly braces
748 // inside the regular expression. The placeholder regexp breaks down as follows:
749 // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
750 // \{([\w\[\]]+)(?:\:\s*( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
751 // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
752 // [^{}\\]+ - anything other than curly braces or backslash
753 // \\. - a backslash escape
754 // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
755 var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
756 searchPlaceholder = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
757 compiled = '^', last = 0, m,
758 segments = this.segments = [],
759 parentParams = parentMatcher ? parentMatcher.params : {},
760 params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
763 function addParameter(id, type, config, location) {
765 if (parentParams[id]) return parentParams[id];
766 if (!/^\w+([-.]+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
767 if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
768 params[id] = new $$UMFP.Param(id, type, config, location);
772 function quoteRegExp(string, pattern, squash, optional) {
773 var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
774 if (!pattern) return result;
776 case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break;
778 result = result.replace(/\/$/, '');
779 surroundPattern = ['(?:\/(', ')|\/)?'];
781 default: surroundPattern = ['(' + squash + "|", ')?']; break;
783 return result + surroundPattern[0] + pattern + surroundPattern[1];
786 this.source = pattern;
788 // Split into static segments separated by path parameter placeholders.
789 // The number of segments is always 1 more than the number of parameters.
790 function matchDetails(m, isSearch) {
791 var id, regexp, segment, type, cfg, arrayMode;
792 id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
793 cfg = config.params[id];
794 segment = pattern.substring(last, m.index);
795 regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
798 type = $$UMFP.type(regexp) || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
802 id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
806 var p, param, segment;
807 while ((m = placeholder.exec(pattern))) {
808 p = matchDetails(m, false);
809 if (p.segment.indexOf('?') >= 0) break; // we're into the search part
811 param = addParameter(p.id, p.type, p.cfg, "path");
812 compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
813 segments.push(p.segment);
814 last = placeholder.lastIndex;
816 segment = pattern.substring(last);
818 // Find any search parameter names and remove them from the last segment
819 var i = segment.indexOf('?');
822 var search = this.sourceSearch = segment.substring(i);
823 segment = segment.substring(0, i);
824 this.sourcePath = pattern.substring(0, last + i);
826 if (search.length > 0) {
828 while ((m = searchPlaceholder.exec(search))) {
829 p = matchDetails(m, true);
830 param = addParameter(p.id, p.type, p.cfg, "search");
831 last = placeholder.lastIndex;
836 this.sourcePath = pattern;
837 this.sourceSearch = '';
840 compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
841 segments.push(segment);
843 this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
844 this.prefix = segments[0];
845 this.$$paramNames = paramNames;
850 * @name ui.router.util.type:UrlMatcher#concat
851 * @methodOf ui.router.util.type:UrlMatcher
854 * Returns a new matcher for a pattern constructed by appending the path part and adding the
855 * search parameters of the specified pattern to this pattern. The current pattern is not
856 * modified. This can be understood as creating a pattern for URLs that are relative to (or
857 * suffixes of) the current pattern.
860 * The following two matchers are equivalent:
862 * new UrlMatcher('/user/{id}?q').concat('/details?date');
863 * new UrlMatcher('/user/{id}/details?q&date');
866 * @param {string} pattern The pattern to append.
867 * @param {Object} config An object hash of the configuration for the matcher.
868 * @returns {UrlMatcher} A matcher for the concatenated pattern.
870 UrlMatcher.prototype.concat = function (pattern, config) {
871 // Because order of search parameters is irrelevant, we can add our own search
872 // parameters to the end of the new pattern. Parse the new pattern by itself
873 // and then join the bits together, but it's much easier to do this on a string level.
874 var defaultConfig = {
875 caseInsensitive: $$UMFP.caseInsensitive(),
876 strict: $$UMFP.strictMode(),
877 squash: $$UMFP.defaultSquashPolicy()
879 return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
882 UrlMatcher.prototype.toString = function () {
888 * @name ui.router.util.type:UrlMatcher#exec
889 * @methodOf ui.router.util.type:UrlMatcher
892 * Tests the specified path against this matcher, and returns an object containing the captured
893 * parameter values, or null if the path does not match. The returned object contains the values
894 * of any search parameters that are mentioned in the pattern, but their value may be null if
895 * they are not present in `searchParams`. This means that search parameters are always treated
900 * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
903 * // returns { id: 'bob', q: 'hello', r: null }
906 * @param {string} path The URL path to match, e.g. `$location.path()`.
907 * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
908 * @returns {Object} The captured parameter values.
910 UrlMatcher.prototype.exec = function (path, searchParams) {
911 var m = this.regexp.exec(path);
913 searchParams = searchParams || {};
915 var paramNames = this.parameters(), nTotal = paramNames.length,
916 nPath = this.segments.length - 1,
917 values = {}, i, j, cfg, paramName;
919 if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
921 function decodePathArray(string) {
922 function reverseString(str) { return str.split("").reverse().join(""); }
923 function unquoteDashes(str) { return str.replace(/\\-/g, "-"); }
925 var split = reverseString(string).split(/-(?!\\)/);
926 var allReversed = map(split, reverseString);
927 return map(allReversed, unquoteDashes).reverse();
931 for (i = 0; i < nPath; i++) {
932 paramName = paramNames[i];
933 param = this.params[paramName];
935 // if the param value matches a pre-replace pair, replace the value before decoding.
936 for (j = 0; j < param.replace.length; j++) {
937 if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
939 if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
940 if (isDefined(paramVal)) paramVal = param.type.decode(paramVal);
941 values[paramName] = param.value(paramVal);
943 for (/**/; i < nTotal; i++) {
944 paramName = paramNames[i];
945 values[paramName] = this.params[paramName].value(searchParams[paramName]);
946 param = this.params[paramName];
947 paramVal = searchParams[paramName];
948 for (j = 0; j < param.replace.length; j++) {
949 if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
951 if (isDefined(paramVal)) paramVal = param.type.decode(paramVal);
952 values[paramName] = param.value(paramVal);
960 * @name ui.router.util.type:UrlMatcher#parameters
961 * @methodOf ui.router.util.type:UrlMatcher
964 * Returns the names of all path and search parameters of this pattern in an unspecified order.
966 * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
967 * pattern has no parameters, an empty array is returned.
969 UrlMatcher.prototype.parameters = function (param) {
970 if (!isDefined(param)) return this.$$paramNames;
971 return this.params[param] || null;
976 * @name ui.router.util.type:UrlMatcher#validates
977 * @methodOf ui.router.util.type:UrlMatcher
980 * Checks an object hash of parameters to validate their correctness according to the parameter
981 * types of this `UrlMatcher`.
983 * @param {Object} params The object hash of parameters to validate.
984 * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
986 UrlMatcher.prototype.validates = function (params) {
987 return this.params.$$validates(params);
992 * @name ui.router.util.type:UrlMatcher#format
993 * @methodOf ui.router.util.type:UrlMatcher
996 * Creates a URL that matches this pattern by substituting the specified values
997 * for the path and search parameters. Null values for path parameters are
998 * treated as empty strings.
1002 * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
1003 * // returns '/user/bob?q=yes'
1006 * @param {Object} values the values to substitute for the parameters in this pattern.
1007 * @returns {string} the formatted URL (path and optionally search part).
1009 UrlMatcher.prototype.format = function (values) {
1010 values = values || {};
1011 var segments = this.segments, params = this.parameters(), paramset = this.params;
1012 if (!this.validates(values)) return null;
1014 var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
1016 function encodeDashes(str) { // Replace dashes with encoded "\-"
1017 return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
1020 for (i = 0; i < nTotal; i++) {
1021 var isPathParam = i < nPath;
1022 var name = params[i], param = paramset[name], value = param.value(values[name]);
1023 var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
1024 var squash = isDefaultValue ? param.squash : false;
1025 var encoded = param.type.encode(value);
1028 var nextSegment = segments[i + 1];
1029 var isFinalPathParam = i + 1 === nPath;
1031 if (squash === false) {
1032 if (encoded != null) {
1033 if (isArray(encoded)) {
1034 result += map(encoded, encodeDashes).join("-");
1036 result += encodeURIComponent(encoded);
1039 result += nextSegment;
1040 } else if (squash === true) {
1041 var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
1042 result += nextSegment.match(capture)[1];
1043 } else if (isString(squash)) {
1044 result += squash + nextSegment;
1047 if (isFinalPathParam && param.squash === true && result.slice(-1) === '/') result = result.slice(0, -1);
1049 if (encoded == null || (isDefaultValue && squash !== false)) continue;
1050 if (!isArray(encoded)) encoded = [ encoded ];
1051 if (encoded.length === 0) continue;
1052 encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
1053 result += (search ? '&' : '?') + (name + '=' + encoded);
1063 * @name ui.router.util.type:Type
1066 * Implements an interface to define custom parameter types that can be decoded from and encoded to
1067 * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
1068 * objects when matching or formatting URLs, or comparing or validating parameter values.
1070 * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
1071 * information on registering custom types.
1073 * @param {Object} config A configuration object which contains the custom type definition. The object's
1074 * properties will override the default methods and/or pattern in `Type`'s public interface.
1078 * decode: function(val) { return parseInt(val, 10); },
1079 * encode: function(val) { return val && val.toString(); },
1080 * equals: function(a, b) { return this.is(a) && a === b; },
1081 * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
1086 * @property {RegExp} pattern The regular expression pattern used to match values of this type when
1087 * coming from a substring of a URL.
1089 * @returns {Object} Returns a new `Type` object.
1091 function Type(config) {
1092 extend(this, config);
1097 * @name ui.router.util.type:Type#is
1098 * @methodOf ui.router.util.type:Type
1101 * Detects whether a value is of a particular type. Accepts a native (decoded) value
1102 * and determines whether it matches the current `Type` object.
1104 * @param {*} val The value to check.
1105 * @param {string} key Optional. If the type check is happening in the context of a specific
1106 * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
1107 * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
1108 * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
1110 Type.prototype.is = function(val, key) {
1116 * @name ui.router.util.type:Type#encode
1117 * @methodOf ui.router.util.type:Type
1120 * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
1121 * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
1122 * only needs to be a representation of `val` that has been coerced to a string.
1124 * @param {*} val The value to encode.
1125 * @param {string} key The name of the parameter in which `val` is stored. Can be used for
1126 * meta-programming of `Type` objects.
1127 * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
1129 Type.prototype.encode = function(val, key) {
1135 * @name ui.router.util.type:Type#decode
1136 * @methodOf ui.router.util.type:Type
1139 * Converts a parameter value (from URL string or transition param) to a custom/native value.
1141 * @param {string} val The URL parameter value to decode.
1142 * @param {string} key The name of the parameter in which `val` is stored. Can be used for
1143 * meta-programming of `Type` objects.
1144 * @returns {*} Returns a custom representation of the URL parameter value.
1146 Type.prototype.decode = function(val, key) {
1152 * @name ui.router.util.type:Type#equals
1153 * @methodOf ui.router.util.type:Type
1156 * Determines whether two decoded values are equivalent.
1158 * @param {*} a A value to compare against.
1159 * @param {*} b A value to compare against.
1160 * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
1162 Type.prototype.equals = function(a, b) {
1166 Type.prototype.$subPattern = function() {
1167 var sub = this.pattern.toString();
1168 return sub.substr(1, sub.length - 2);
1171 Type.prototype.pattern = /.*/;
1173 Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
1175 /** Given an encoded string, or a decoded object, returns a decoded object */
1176 Type.prototype.$normalize = function(val) {
1177 return this.is(val) ? val : this.decode(val);
1181 * Wraps an existing custom Type as an array of Type, depending on 'mode'.
1183 * - urlmatcher pattern "/path?{queryParam[]:int}"
1184 * - url: "/path?queryParam=1&queryParam=2
1185 * - $stateParams.queryParam will be [1, 2]
1186 * if `mode` is "auto", then
1187 * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
1188 * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
1190 Type.prototype.$asArray = function(mode, isSearch) {
1191 if (!mode) return this;
1192 if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
1194 function ArrayType(type, mode) {
1195 function bindTo(type, callbackName) {
1197 return type[callbackName].apply(type, arguments);
1201 // Wrap non-array value as array
1202 function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
1203 // Unwrap array value for "auto" mode. Return undefined for empty array.
1204 function arrayUnwrap(val) {
1205 switch(val.length) {
1206 case 0: return undefined;
1207 case 1: return mode === "auto" ? val[0] : val;
1208 default: return val;
1211 function falsey(val) { return !val; }
1213 // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
1214 function arrayHandler(callback, allTruthyMode) {
1215 return function handleArray(val) {
1216 if (isArray(val) && val.length === 0) return val;
1217 val = arrayWrap(val);
1218 var result = map(val, callback);
1219 if (allTruthyMode === true)
1220 return filter(result, falsey).length === 0;
1221 return arrayUnwrap(result);
1225 // Wraps type (.equals) functions to operate on each value of an array
1226 function arrayEqualsHandler(callback) {
1227 return function handleArray(val1, val2) {
1228 var left = arrayWrap(val1), right = arrayWrap(val2);
1229 if (left.length !== right.length) return false;
1230 for (var i = 0; i < left.length; i++) {
1231 if (!callback(left[i], right[i])) return false;
1237 this.encode = arrayHandler(bindTo(type, 'encode'));
1238 this.decode = arrayHandler(bindTo(type, 'decode'));
1239 this.is = arrayHandler(bindTo(type, 'is'), true);
1240 this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
1241 this.pattern = type.pattern;
1242 this.$normalize = arrayHandler(bindTo(type, '$normalize'));
1243 this.name = type.name;
1244 this.$arrayMode = mode;
1247 return new ArrayType(this, mode);
1254 * @name ui.router.util.$urlMatcherFactory
1257 * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
1258 * is also available to providers under the name `$urlMatcherFactoryProvider`.
1260 function $UrlMatcherFactory() {
1263 var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
1265 // Use tildes to pre-encode slashes.
1266 // If the slashes are simply URLEncoded, the browser can choose to pre-decode them,
1267 // and bidirectional encoding/decoding fails.
1268 // Tilde was chosen because it's not a RFC 3986 section 2.2 Reserved Character
1269 function valToString(val) { return val != null ? val.toString().replace(/~/g, "~~").replace(/\//g, "~2F") : val; }
1270 function valFromString(val) { return val != null ? val.toString().replace(/~2F/g, "/").replace(/~~/g, "~") : val; }
1272 var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
1274 encode: valToString,
1275 decode: valFromString,
1276 // TODO: in 1.0, make string .is() return false if value is undefined/null by default.
1277 // In 0.2.x, string params are optional by default for backwards compat
1278 is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; },
1282 encode: valToString,
1283 decode: function(val) { return parseInt(val, 10); },
1284 is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
1288 encode: function(val) { return val ? 1 : 0; },
1289 decode: function(val) { return parseInt(val, 10) !== 0; },
1290 is: function(val) { return val === true || val === false; },
1294 encode: function (val) {
1297 return [ val.getFullYear(),
1298 ('0' + (val.getMonth() + 1)).slice(-2),
1299 ('0' + val.getDate()).slice(-2)
1302 decode: function (val) {
1303 if (this.is(val)) return val;
1304 var match = this.capture.exec(val);
1305 return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
1307 is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },
1308 equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },
1309 pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
1310 capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
1313 encode: angular.toJson,
1314 decode: angular.fromJson,
1315 is: angular.isObject,
1316 equals: angular.equals,
1319 any: { // does not encode/decode
1320 encode: angular.identity,
1321 decode: angular.identity,
1322 equals: angular.equals,
1327 function getDefaultConfig() {
1329 strict: isStrictMode,
1330 caseInsensitive: isCaseInsensitive
1334 function isInjectable(value) {
1335 return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
1339 * [Internal] Get the default value of a parameter, which may be an injectable function.
1341 $UrlMatcherFactory.$$getDefaultValue = function(config) {
1342 if (!isInjectable(config.value)) return config.value;
1343 if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
1344 return injector.invoke(config.value);
1349 * @name ui.router.util.$urlMatcherFactory#caseInsensitive
1350 * @methodOf ui.router.util.$urlMatcherFactory
1353 * Defines whether URL matching should be case sensitive (the default behavior), or not.
1355 * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
1356 * @returns {boolean} the current value of caseInsensitive
1358 this.caseInsensitive = function(value) {
1359 if (isDefined(value))
1360 isCaseInsensitive = value;
1361 return isCaseInsensitive;
1366 * @name ui.router.util.$urlMatcherFactory#strictMode
1367 * @methodOf ui.router.util.$urlMatcherFactory
1370 * Defines whether URLs should match trailing slashes, or not (the default behavior).
1372 * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
1373 * @returns {boolean} the current value of strictMode
1375 this.strictMode = function(value) {
1376 if (isDefined(value))
1377 isStrictMode = value;
1378 return isStrictMode;
1383 * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
1384 * @methodOf ui.router.util.$urlMatcherFactory
1387 * Sets the default behavior when generating or matching URLs with default parameter values.
1389 * @param {string} value A string that defines the default parameter URL squashing behavior.
1390 * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
1391 * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
1392 * parameter is surrounded by slashes, squash (remove) one slash from the URL
1393 * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
1394 * the parameter value from the URL and replace it with this string.
1396 this.defaultSquashPolicy = function(value) {
1397 if (!isDefined(value)) return defaultSquashPolicy;
1398 if (value !== true && value !== false && !isString(value))
1399 throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
1400 defaultSquashPolicy = value;
1406 * @name ui.router.util.$urlMatcherFactory#compile
1407 * @methodOf ui.router.util.$urlMatcherFactory
1410 * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
1412 * @param {string} pattern The URL pattern.
1413 * @param {Object} config The config object hash.
1414 * @returns {UrlMatcher} The UrlMatcher.
1416 this.compile = function (pattern, config) {
1417 return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
1422 * @name ui.router.util.$urlMatcherFactory#isMatcher
1423 * @methodOf ui.router.util.$urlMatcherFactory
1426 * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
1428 * @param {Object} object The object to perform the type check against.
1429 * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
1430 * implementing all the same methods.
1432 this.isMatcher = function (o) {
1433 if (!isObject(o)) return false;
1436 forEach(UrlMatcher.prototype, function(val, name) {
1437 if (isFunction(val)) {
1438 result = result && (isDefined(o[name]) && isFunction(o[name]));
1446 * @name ui.router.util.$urlMatcherFactory#type
1447 * @methodOf ui.router.util.$urlMatcherFactory
1450 * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
1451 * generate URLs with typed parameters.
1453 * @param {string} name The type name.
1454 * @param {Object|Function} definition The type definition. See
1455 * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
1456 * @param {Object|Function} definitionFn (optional) A function that is injected before the app
1457 * runtime starts. The result of this function is merged into the existing `definition`.
1458 * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
1460 * @returns {Object} Returns `$urlMatcherFactoryProvider`.
1463 * This is a simple example of a custom type that encodes and decodes items from an
1464 * array, using the array index as the URL-encoded value:
1467 * var list = ['John', 'Paul', 'George', 'Ringo'];
1469 * $urlMatcherFactoryProvider.type('listItem', {
1470 * encode: function(item) {
1471 * // Represent the list item in the URL using its corresponding index
1472 * return list.indexOf(item);
1474 * decode: function(item) {
1475 * // Look up the list item by index
1476 * return list[parseInt(item, 10)];
1478 * is: function(item) {
1479 * // Ensure the item is valid by checking to see that it appears
1481 * return list.indexOf(item) > -1;
1485 * $stateProvider.state('list', {
1486 * url: "/list/{item:listItem}",
1487 * controller: function($scope, $stateParams) {
1488 * console.log($stateParams.item);
1494 * // Changes URL to '/list/3', logs "Ringo" to the console
1495 * $state.go('list', { item: "Ringo" });
1498 * This is a more complex example of a type that relies on dependency injection to
1499 * interact with services, and uses the parameter name from the URL to infer how to
1500 * handle encoding and decoding parameter values:
1503 * // Defines a custom type that gets a value from a service,
1504 * // where each service gets different types of values from
1506 * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
1508 * // Matches up services to URL parameter names
1515 * encode: function(object) {
1516 * // Represent the object in the URL using its unique ID
1519 * decode: function(value, key) {
1520 * // Look up the object by ID, using the parameter
1521 * // name (key) to call the correct service
1522 * return services[key].findById(value);
1524 * is: function(object, key) {
1525 * // Check that object is a valid dbObject
1526 * return angular.isObject(object) && object.id && services[key];
1528 * equals: function(a, b) {
1529 * // Check the equality of decoded objects by comparing
1530 * // their unique IDs
1531 * return a.id === b.id;
1536 * // In a config() block, you can then attach URLs with
1537 * // type-annotated parameters:
1538 * $stateProvider.state('users', {
1541 * }).state('users.item', {
1542 * url: "/{user:dbObject}",
1543 * controller: function($scope, $stateParams) {
1544 * // $stateParams.user will now be an object returned from
1545 * // the Users service
1551 this.type = function (name, definition, definitionFn) {
1552 if (!isDefined(definition)) return $types[name];
1553 if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
1555 $types[name] = new Type(extend({ name: name }, definition));
1557 typeQueue.push({ name: name, def: definitionFn });
1558 if (!enqueue) flushTypeQueue();
1563 // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
1564 function flushTypeQueue() {
1565 while(typeQueue.length) {
1566 var type = typeQueue.shift();
1567 if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
1568 angular.extend($types[type.name], injector.invoke(type.def));
1572 // Register default types. Store them in the prototype of $types.
1573 forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
1574 $types = inherit($types, {});
1576 /* No need to document $get, since it returns this */
1577 this.$get = ['$injector', function ($injector) {
1578 injector = $injector;
1582 forEach(defaultTypes, function(type, name) {
1583 if (!$types[name]) $types[name] = new Type(type);
1588 this.Param = function Param(id, type, config, location) {
1590 config = unwrapShorthand(config);
1591 type = getType(config, type, location);
1592 var arrayMode = getArrayMode();
1593 type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
1594 if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
1595 config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
1596 var isOptional = config.value !== undefined;
1597 var squash = getSquashPolicy(config, isOptional);
1598 var replace = getReplace(config, arrayMode, isOptional, squash);
1600 function unwrapShorthand(config) {
1601 var keys = isObject(config) ? objectKeys(config) : [];
1602 var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
1603 indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
1604 if (isShorthand) config = { value: config };
1605 config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
1609 function getType(config, urlType, location) {
1610 if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
1611 if (urlType) return urlType;
1612 if (!config.type) return (location === "config" ? $types.any : $types.string);
1614 if (angular.isString(config.type))
1615 return $types[config.type];
1616 if (config.type instanceof Type)
1618 return new Type(config.type);
1621 // array config: param name (param[]) overrides default settings. explicit config overrides param name.
1622 function getArrayMode() {
1623 var arrayDefaults = { array: (location === "search" ? "auto" : false) };
1624 var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
1625 return extend(arrayDefaults, arrayParamNomenclature, config).array;
1629 * returns false, true, or the squash value to indicate the "default parameter url squash policy".
1631 function getSquashPolicy(config, isOptional) {
1632 var squash = config.squash;
1633 if (!isOptional || squash === false) return false;
1634 if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
1635 if (squash === true || isString(squash)) return squash;
1636 throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
1639 function getReplace(config, arrayMode, isOptional, squash) {
1640 var replace, configuredKeys, defaultPolicy = [
1641 { from: "", to: (isOptional || arrayMode ? undefined : "") },
1642 { from: null, to: (isOptional || arrayMode ? undefined : "") }
1644 replace = isArray(config.replace) ? config.replace : [];
1645 if (isString(squash))
1646 replace.push({ from: squash, to: undefined });
1647 configuredKeys = map(replace, function(item) { return item.from; } );
1648 return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
1652 * [Internal] Get the default value of a parameter, which may be an injectable function.
1654 function $$getDefaultValue() {
1655 if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
1656 var defaultValue = injector.invoke(config.$$fn);
1657 if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))
1658 throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")");
1659 return defaultValue;
1663 * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
1664 * default value, which may be the result of an injectable function.
1666 function $value(value) {
1667 function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
1668 function $replace(value) {
1669 var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
1670 return replacement.length ? replacement[0] : value;
1672 value = $replace(value);
1673 return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);
1676 function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
1685 isOptional: isOptional,
1693 function ParamSet(params) {
1694 extend(this, params || {});
1697 ParamSet.prototype = {
1699 return inherit(this, extend(new ParamSet(), { $$parent: this}));
1701 $$keys: function () {
1702 var keys = [], chain = [], parent = this,
1703 ignore = objectKeys(ParamSet.prototype);
1704 while (parent) { chain.push(parent); parent = parent.$$parent; }
1706 forEach(chain, function(paramset) {
1707 forEach(objectKeys(paramset), function(key) {
1708 if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
1713 $$values: function(paramValues) {
1714 var values = {}, self = this;
1715 forEach(self.$$keys(), function(key) {
1716 values[key] = self[key].value(paramValues && paramValues[key]);
1720 $$equals: function(paramValues1, paramValues2) {
1721 var equal = true, self = this;
1722 forEach(self.$$keys(), function(key) {
1723 var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
1724 if (!self[key].type.equals(left, right)) equal = false;
1728 $$validates: function $$validate(paramValues) {
1729 var keys = this.$$keys(), i, param, rawVal, normalized, encoded;
1730 for (i = 0; i < keys.length; i++) {
1731 param = this[keys[i]];
1732 rawVal = paramValues[keys[i]];
1733 if ((rawVal === undefined || rawVal === null) && param.isOptional)
1734 break; // There was no parameter value, but the param is optional
1735 normalized = param.type.$normalize(rawVal);
1736 if (!param.type.is(normalized))
1737 return false; // The value was not of the correct Type, and could not be decoded to the correct Type
1738 encoded = param.type.encode(normalized);
1739 if (angular.isString(encoded) && !param.type.pattern.exec(encoded))
1740 return false; // The value was of the correct type, but when encoded, did not match the Type's regexp
1747 this.ParamSet = ParamSet;
1750 // Register as a provider so it's available to other providers
1751 angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
1752 angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
1756 * @name ui.router.router.$urlRouterProvider
1758 * @requires ui.router.util.$urlMatcherFactoryProvider
1759 * @requires $locationProvider
1762 * `$urlRouterProvider` has the responsibility of watching `$location`.
1763 * When `$location` changes it runs through a list of rules one by one until a
1764 * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
1765 * a url in a state configuration. All urls are compiled into a UrlMatcher object.
1767 * There are several methods on `$urlRouterProvider` that make it useful to use directly
1768 * in your module config.
1770 $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
1771 function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
1772 var rules = [], otherwise = null, interceptDeferred = false, listener;
1774 // Returns a string that is a prefix of all strings matching the RegExp
1775 function regExpPrefix(re) {
1776 var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
1777 return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
1780 // Interpolates matched values into a String.replace()-style pattern
1781 function interpolate(pattern, match) {
1782 return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
1783 return match[what === '$' ? 0 : Number(what)];
1789 * @name ui.router.router.$urlRouterProvider#rule
1790 * @methodOf ui.router.router.$urlRouterProvider
1793 * Defines rules that are used by `$urlRouterProvider` to find matches for
1798 * var app = angular.module('app', ['ui.router.router']);
1800 * app.config(function ($urlRouterProvider) {
1801 * // Here's an example of how you might allow case insensitive urls
1802 * $urlRouterProvider.rule(function ($injector, $location) {
1803 * var path = $location.path(),
1804 * normalized = path.toLowerCase();
1806 * if (path !== normalized) {
1807 * return normalized;
1813 * @param {function} rule Handler function that takes `$injector` and `$location`
1814 * services as arguments. You can use them to return a valid path as a string.
1816 * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
1818 this.rule = function (rule) {
1819 if (!isFunction(rule)) throw new Error("'rule' must be a function");
1826 * @name ui.router.router.$urlRouterProvider#otherwise
1827 * @methodOf ui.router.router.$urlRouterProvider
1830 * Defines a path that is used when an invalid route is requested.
1834 * var app = angular.module('app', ['ui.router.router']);
1836 * app.config(function ($urlRouterProvider) {
1837 * // if the path doesn't match any of the urls you configured
1838 * // otherwise will take care of routing the user to the
1840 * $urlRouterProvider.otherwise('/index');
1842 * // Example of using function rule as param
1843 * $urlRouterProvider.otherwise(function ($injector, $location) {
1844 * return '/a/valid/url';
1849 * @param {string|function} rule The url path you want to redirect to or a function
1850 * rule that returns the url path. The function version is passed two params:
1851 * `$injector` and `$location` services, and must return a url string.
1853 * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
1855 this.otherwise = function (rule) {
1856 if (isString(rule)) {
1857 var redirect = rule;
1858 rule = function () { return redirect; };
1860 else if (!isFunction(rule)) throw new Error("'rule' must be a function");
1866 function handleIfMatch($injector, handler, match) {
1867 if (!match) return false;
1868 var result = $injector.invoke(handler, handler, { $match: match });
1869 return isDefined(result) ? result : true;
1874 * @name ui.router.router.$urlRouterProvider#when
1875 * @methodOf ui.router.router.$urlRouterProvider
1878 * Registers a handler for a given url matching.
1880 * If the handler is a string, it is
1881 * treated as a redirect, and is interpolated according to the syntax of match
1882 * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
1884 * If the handler is a function, it is injectable. It gets invoked if `$location`
1885 * matches. You have the option of inject the match object as `$match`.
1887 * The handler can return
1889 * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
1890 * will continue trying to find another one that matches.
1891 * - **string** which is treated as a redirect and passed to `$location.url()`
1892 * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
1896 * var app = angular.module('app', ['ui.router.router']);
1898 * app.config(function ($urlRouterProvider) {
1899 * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
1900 * if ($state.$current.navigable !== state ||
1901 * !equalForKeys($match, $stateParams) {
1902 * $state.transitionTo(state, $match, false);
1908 * @param {string|object} what The incoming path that you want to redirect.
1909 * @param {string|function} handler The path you want to redirect your user to.
1911 this.when = function (what, handler) {
1912 var redirect, handlerIsString = isString(handler);
1913 if (isString(what)) what = $urlMatcherFactory.compile(what);
1915 if (!handlerIsString && !isFunction(handler) && !isArray(handler))
1916 throw new Error("invalid 'handler' in when()");
1919 matcher: function (what, handler) {
1920 if (handlerIsString) {
1921 redirect = $urlMatcherFactory.compile(handler);
1922 handler = ['$match', function ($match) { return redirect.format($match); }];
1924 return extend(function ($injector, $location) {
1925 return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
1927 prefix: isString(what.prefix) ? what.prefix : ''
1930 regex: function (what, handler) {
1931 if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
1933 if (handlerIsString) {
1935 handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
1937 return extend(function ($injector, $location) {
1938 return handleIfMatch($injector, handler, what.exec($location.path()));
1940 prefix: regExpPrefix(what)
1945 var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
1947 for (var n in check) {
1948 if (check[n]) return this.rule(strategies[n](what, handler));
1951 throw new Error("invalid 'what' in when()");
1956 * @name ui.router.router.$urlRouterProvider#deferIntercept
1957 * @methodOf ui.router.router.$urlRouterProvider
1960 * Disables (or enables) deferring location change interception.
1962 * If you wish to customize the behavior of syncing the URL (for example, if you wish to
1963 * defer a transition but maintain the current URL), call this method at configuration time.
1964 * Then, at run time, call `$urlRouter.listen()` after you have configured your own
1965 * `$locationChangeSuccess` event handler.
1969 * var app = angular.module('app', ['ui.router.router']);
1971 * app.config(function ($urlRouterProvider) {
1973 * // Prevent $urlRouter from automatically intercepting URL changes;
1974 * // this allows you to configure custom behavior in between
1975 * // location changes and route synchronization:
1976 * $urlRouterProvider.deferIntercept();
1978 * }).run(function ($rootScope, $urlRouter, UserService) {
1980 * $rootScope.$on('$locationChangeSuccess', function(e) {
1981 * // UserService is an example service for managing user state
1982 * if (UserService.isLoggedIn()) return;
1984 * // Prevent $urlRouter's default handler from firing
1985 * e.preventDefault();
1987 * UserService.handleLogin().then(function() {
1988 * // Once the user has logged in, sync the current URL
1990 * $urlRouter.sync();
1994 * // Configures $urlRouter's listener *after* your custom listener
1995 * $urlRouter.listen();
1999 * @param {boolean} defer Indicates whether to defer location change interception. Passing
2000 no parameter is equivalent to `true`.
2002 this.deferIntercept = function (defer) {
2003 if (defer === undefined) defer = true;
2004 interceptDeferred = defer;
2009 * @name ui.router.router.$urlRouter
2011 * @requires $location
2012 * @requires $rootScope
2013 * @requires $injector
2014 * @requires $browser
2020 $get.$inject = ['$location', '$rootScope', '$injector', '$browser', '$sniffer'];
2021 function $get( $location, $rootScope, $injector, $browser, $sniffer) {
2023 var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
2025 function appendBasePath(url, isHtml5, absolute) {
2026 if (baseHref === '/') return url;
2027 if (isHtml5) return baseHref.slice(0, -1) + url;
2028 if (absolute) return baseHref.slice(1) + url;
2032 // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
2033 function update(evt) {
2034 if (evt && evt.defaultPrevented) return;
2035 var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
2036 lastPushedUrl = undefined;
2037 // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573
2038 //if (ignoreUpdate) return true;
2040 function check(rule) {
2041 var handled = rule($injector, $location);
2043 if (!handled) return false;
2044 if (isString(handled)) $location.replace().url(handled);
2047 var n = rules.length, i;
2049 for (i = 0; i < n; i++) {
2050 if (check(rules[i])) return;
2052 // always check otherwise last to allow dynamic updates to the set of rules
2053 if (otherwise) check(otherwise);
2057 listener = listener || $rootScope.$on('$locationChangeSuccess', update);
2061 rules.sort(function(ruleA, ruleB) {
2062 var aLength = ruleA.prefix ? ruleA.prefix.length : 0;
2063 var bLength = ruleB.prefix ? ruleB.prefix.length : 0;
2064 return bLength - aLength;
2067 if (!interceptDeferred) listen();
2072 * @name ui.router.router.$urlRouter#sync
2073 * @methodOf ui.router.router.$urlRouter
2076 * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
2077 * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
2078 * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
2079 * with the transition by calling `$urlRouter.sync()`.
2083 * angular.module('app', ['ui.router'])
2084 * .run(function($rootScope, $urlRouter) {
2085 * $rootScope.$on('$locationChangeSuccess', function(evt) {
2086 * // Halt state change from even starting
2087 * evt.preventDefault();
2088 * // Perform custom logic
2089 * var meetsRequirement = ...
2090 * // Continue with the update and state transition if logic allows
2091 * if (meetsRequirement) $urlRouter.sync();
2100 listen: function() {
2104 update: function(read) {
2106 location = $location.url();
2109 if ($location.url() === location) return;
2111 $location.url(location);
2112 $location.replace();
2115 push: function(urlMatcher, params, options) {
2116 var url = urlMatcher.format(params || {});
2118 // Handle the special hash param, if needed
2119 if (url !== null && params && params['#']) {
2120 url += '#' + params['#'];
2124 lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
2125 if (options && options.replace) $location.replace();
2130 * @name ui.router.router.$urlRouter#href
2131 * @methodOf ui.router.router.$urlRouter
2134 * A URL generation method that returns the compiled URL for a given
2135 * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
2139 * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
2142 * // $bob == "/about/bob";
2145 * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
2146 * @param {object=} params An object of parameter values to fill the matcher's required parameters.
2147 * @param {object=} options Options object. The options are:
2149 * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
2151 * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
2153 href: function(urlMatcher, params, options) {
2154 if (!urlMatcher.validates(params)) return null;
2156 var isHtml5 = $locationProvider.html5Mode();
2157 if (angular.isObject(isHtml5)) {
2158 isHtml5 = isHtml5.enabled;
2161 isHtml5 = isHtml5 && $sniffer.history;
2163 var url = urlMatcher.format(params);
2164 options = options || {};
2166 if (!isHtml5 && url !== null) {
2167 url = "#" + $locationProvider.hashPrefix() + url;
2170 // Handle special hash param, if needed
2171 if (url !== null && params && params['#']) {
2172 url += '#' + params['#'];
2175 url = appendBasePath(url, isHtml5, options.absolute);
2177 if (!options.absolute || !url) {
2181 var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
2182 port = (port === 80 || port === 443 ? '' : ':' + port);
2184 return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
2190 angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
2194 * @name ui.router.state.$stateProvider
2196 * @requires ui.router.router.$urlRouterProvider
2197 * @requires ui.router.util.$urlMatcherFactoryProvider
2200 * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
2203 * A state corresponds to a "place" in the application in terms of the overall UI and
2204 * navigation. A state describes (via the controller / template / view properties) what
2205 * the UI looks like and does at that place.
2207 * States often have things in common, and the primary way of factoring out these
2208 * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
2211 * The `$stateProvider` provides interfaces to declare these states for your app.
2213 $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
2214 function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
2216 var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
2218 // Builds state properties from definition passed to registerState()
2219 var stateBuilder = {
2221 // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
2222 // state.children = [];
2223 // if (parent) parent.children.push(state);
2224 parent: function(state) {
2225 if (isDefined(state.parent) && state.parent) return findState(state.parent);
2226 // regex matches any valid composite state name
2227 // would match "contact.list" but not "contacts"
2228 var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
2229 return compositeName ? findState(compositeName[1]) : root;
2232 // inherit 'data' from parent and override by own values (if any)
2233 data: function(state) {
2234 if (state.parent && state.parent.data) {
2235 state.data = state.self.data = inherit(state.parent.data, state.data);
2240 // Build a URLMatcher if necessary, either via a relative or absolute URL
2241 url: function(state) {
2242 var url = state.url, config = { params: state.params || {} };
2244 if (isString(url)) {
2245 if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
2246 return (state.parent.navigable || root).url.concat(url, config);
2249 if (!url || $urlMatcherFactory.isMatcher(url)) return url;
2250 throw new Error("Invalid url '" + url + "' in state '" + state + "'");
2253 // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
2254 navigable: function(state) {
2255 return state.url ? state : (state.parent ? state.parent.navigable : null);
2258 // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
2259 ownParams: function(state) {
2260 var params = state.url && state.url.params || new $$UMFP.ParamSet();
2261 forEach(state.params || {}, function(config, id) {
2262 if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
2267 // Derive parameters for this state and ensure they're a super-set of parent's parameters
2268 params: function(state) {
2269 return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
2272 // If there is no explicit multi-view configuration, make one up so we don't have
2273 // to handle both cases in the view directive later. Note that having an explicit
2274 // 'views' property will mean the default unnamed view properties are ignored. This
2275 // is also a good time to resolve view names to absolute names, so everything is a
2276 // straight lookup at link time.
2277 views: function(state) {
2280 forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
2281 if (name.indexOf('@') < 0) name += '@' + state.parent.name;
2287 // Keep a full path from the root down to this state as this is needed for state activation.
2288 path: function(state) {
2289 return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
2292 // Speed up $state.contains() as it's used a lot
2293 includes: function(state) {
2294 var includes = state.parent ? extend({}, state.parent.includes) : {};
2295 includes[state.name] = true;
2302 function isRelative(stateName) {
2303 return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
2306 function findState(stateOrName, base) {
2307 if (!stateOrName) return undefined;
2309 var isStr = isString(stateOrName),
2310 name = isStr ? stateOrName : stateOrName.name,
2311 path = isRelative(name);
2314 if (!base) throw new Error("No reference point given for path '" + name + "'");
2315 base = findState(base);
2317 var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
2319 for (; i < pathLength; i++) {
2320 if (rel[i] === "" && i === 0) {
2324 if (rel[i] === "^") {
2325 if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
2326 current = current.parent;
2331 rel = rel.slice(i).join(".");
2332 name = current.name + (current.name && rel ? "." : "") + rel;
2334 var state = states[name];
2336 if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
2342 function queueState(parentName, state) {
2343 if (!queue[parentName]) {
2344 queue[parentName] = [];
2346 queue[parentName].push(state);
2349 function flushQueuedChildren(parentName) {
2350 var queued = queue[parentName] || [];
2351 while(queued.length) {
2352 registerState(queued.shift());
2356 function registerState(state) {
2357 // Wrap a new object around the state so we can store our private details easily.
2358 state = inherit(state, {
2360 resolve: state.resolve || {},
2361 toString: function() { return this.name; }
2364 var name = state.name;
2365 if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
2366 if (states.hasOwnProperty(name)) throw new Error("State '" + name + "' is already defined");
2369 var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
2370 : (isString(state.parent)) ? state.parent
2371 : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
2374 // If parent is not registered yet, add state to queue and register later
2375 if (parentName && !states[parentName]) {
2376 return queueState(parentName, state.self);
2379 for (var key in stateBuilder) {
2380 if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
2382 states[name] = state;
2384 // Register the state in the global state list and with $urlRouter if necessary.
2385 if (!state[abstractKey] && state.url) {
2386 $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
2387 if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
2388 $state.transitionTo(state, $match, { inherit: true, location: false });
2393 // Register any queued children
2394 flushQueuedChildren(name);
2399 // Checks text to see if it looks like a glob.
2400 function isGlob (text) {
2401 return text.indexOf('*') > -1;
2404 // Returns true if glob matches current $state name.
2405 function doesStateMatchGlob (glob) {
2406 var globSegments = glob.split('.'),
2407 segments = $state.$current.name.split('.');
2409 //match single stars
2410 for (var i = 0, l = globSegments.length; i < l; i++) {
2411 if (globSegments[i] === '*') {
2416 //match greedy starts
2417 if (globSegments[0] === '**') {
2418 segments = segments.slice(indexOf(segments, globSegments[1]));
2419 segments.unshift('**');
2422 if (globSegments[globSegments.length - 1] === '**') {
2423 segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
2424 segments.push('**');
2427 if (globSegments.length != segments.length) {
2431 return segments.join('') === globSegments.join('');
2435 // Implicit root state that is always active
2436 root = registerState({
2442 root.navigable = null;
2447 * @name ui.router.state.$stateProvider#decorator
2448 * @methodOf ui.router.state.$stateProvider
2451 * Allows you to extend (carefully) or override (at your own peril) the
2452 * `stateBuilder` object used internally by `$stateProvider`. This can be used
2453 * to add custom functionality to ui-router, for example inferring templateUrl
2454 * based on the state name.
2456 * When passing only a name, it returns the current (original or decorated) builder
2457 * function that matches `name`.
2459 * The builder functions that can be decorated are listed below. Though not all
2460 * necessarily have a good use case for decoration, that is up to you to decide.
2462 * In addition, users can attach custom decorators, which will generate new
2463 * properties within the state's internal definition. There is currently no clear
2464 * use-case for this beyond accessing internal states (i.e. $state.$current),
2465 * however, expect this to become increasingly relevant as we introduce additional
2466 * meta-programming features.
2468 * **Warning**: Decorators should not be interdependent because the order of
2469 * execution of the builder functions in non-deterministic. Builder functions
2470 * should only be dependent on the state definition object and super function.
2473 * Existing builder functions and current return values:
2475 * - **parent** `{object}` - returns the parent state object.
2476 * - **data** `{object}` - returns state data, including any inherited data that is not
2477 * overridden by own values (if any).
2478 * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
2480 * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
2482 * - **params** `{object}` - returns an array of state params that are ensured to
2483 * be a super-set of parent's params.
2484 * - **views** `{object}` - returns a views object where each key is an absolute view
2485 * name (i.e. "viewName@stateName") and each value is the config object
2486 * (template, controller) for the view. Even when you don't use the views object
2487 * explicitly on a state config, one is still created for you internally.
2488 * So by decorating this builder function you have access to decorating template
2489 * and controller properties.
2490 * - **ownParams** `{object}` - returns an array of params that belong to the state,
2491 * not including any params defined by ancestor states.
2492 * - **path** `{string}` - returns the full path from the root down to this state.
2493 * Needed for state activation.
2494 * - **includes** `{object}` - returns an object that includes every state that
2495 * would pass a `$state.includes()` test.
2499 * // Override the internal 'views' builder with a function that takes the state
2500 * // definition, and a reference to the internal function being overridden:
2501 * $stateProvider.decorator('views', function (state, parent) {
2503 * views = parent(state);
2505 * angular.forEach(views, function (config, name) {
2506 * var autoName = (state.name + '.' + name).replace('.', '/');
2507 * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
2508 * result[name] = config;
2513 * $stateProvider.state('home', {
2515 * 'contact.list': { controller: 'ListController' },
2516 * 'contact.item': { controller: 'ItemController' }
2522 * $state.go('home');
2523 * // Auto-populates list and item views with /partials/home/contact/list.html,
2524 * // and /partials/home/contact/item.html, respectively.
2527 * @param {string} name The name of the builder function to decorate.
2528 * @param {object} func A function that is responsible for decorating the original
2529 * builder function. The function receives two parameters:
2531 * - `{object}` - state - The state config object.
2532 * - `{object}` - super - The original builder function.
2534 * @return {object} $stateProvider - $stateProvider instance
2536 this.decorator = decorator;
2537 function decorator(name, func) {
2538 /*jshint validthis: true */
2539 if (isString(name) && !isDefined(func)) {
2540 return stateBuilder[name];
2542 if (!isFunction(func) || !isString(name)) {
2545 if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
2546 stateBuilder.$delegates[name] = stateBuilder[name];
2548 stateBuilder[name] = func;
2554 * @name ui.router.state.$stateProvider#state
2555 * @methodOf ui.router.state.$stateProvider
2558 * Registers a state configuration under a given state name. The stateConfig object
2559 * has the following acceptable properties.
2561 * @param {string} name A unique state name, e.g. "home", "about", "contacts".
2562 * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
2563 * @param {object} stateConfig State configuration object.
2564 * @param {string|function=} stateConfig.template
2565 * <a id='template'></a>
2566 * html template as a string or a function that returns
2567 * an html template as a string which should be used by the uiView directives. This property
2568 * takes precedence over templateUrl.
2570 * If `template` is a function, it will be called with the following parameters:
2572 * - {array.<object>} - state parameters extracted from the current $location.path() by
2573 * applying the current state
2576 * "<h1>inline template definition</h1>" +
2577 * "<div ui-view></div>"</pre>
2578 * <pre>template: function(params) {
2579 * return "<h1>generated template</h1>"; }</pre>
2582 * @param {string|function=} stateConfig.templateUrl
2583 * <a id='templateUrl'></a>
2585 * path or function that returns a path to an html
2586 * template that should be used by uiView.
2588 * If `templateUrl` is a function, it will be called with the following parameters:
2590 * - {array.<object>} - state parameters extracted from the current $location.path() by
2591 * applying the current state
2593 * <pre>templateUrl: "home.html"</pre>
2594 * <pre>templateUrl: function(params) {
2595 * return myTemplates[params.pageId]; }</pre>
2597 * @param {function=} stateConfig.templateProvider
2598 * <a id='templateProvider'></a>
2599 * Provider function that returns HTML content string.
2600 * <pre> templateProvider:
2601 * function(MyTemplateService, params) {
2602 * return MyTemplateService.getTemplate(params.pageId);
2605 * @param {string|function=} stateConfig.controller
2606 * <a id='controller'></a>
2608 * Controller fn that should be associated with newly
2609 * related scope or the name of a registered controller if passed as a string.
2610 * Optionally, the ControllerAs may be declared here.
2611 * <pre>controller: "MyRegisteredController"</pre>
2613 * "MyRegisteredController as fooCtrl"}</pre>
2614 * <pre>controller: function($scope, MyService) {
2615 * $scope.data = MyService.getData(); }</pre>
2617 * @param {function=} stateConfig.controllerProvider
2618 * <a id='controllerProvider'></a>
2620 * Injectable provider function that returns the actual controller or string.
2621 * <pre>controllerProvider:
2622 * function(MyResolveData) {
2623 * if (MyResolveData.foo)
2625 * else if (MyResolveData.bar)
2627 * else return function($scope) {
2628 * $scope.baz = "Qux";
2632 * @param {string=} stateConfig.controllerAs
2633 * <a id='controllerAs'></a>
2635 * A controller alias name. If present the controller will be
2636 * published to scope under the controllerAs name.
2637 * <pre>controllerAs: "myCtrl"</pre>
2639 * @param {string|object=} stateConfig.parent
2640 * <a id='parent'></a>
2641 * Optionally specifies the parent state of this state.
2643 * <pre>parent: 'parentState'</pre>
2644 * <pre>parent: parentState // JS variable</pre>
2646 * @param {object=} stateConfig.resolve
2647 * <a id='resolve'></a>
2649 * An optional map<string, function> of dependencies which
2650 * should be injected into the controller. If any of these dependencies are promises,
2651 * the router will wait for them all to be resolved before the controller is instantiated.
2652 * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
2653 * and the values of the resolved promises are injected into any controllers that reference them.
2654 * If any of the promises are rejected the $stateChangeError event is fired.
2656 * The map object is:
2658 * - key - {string}: name of dependency to be injected into controller
2659 * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
2660 * it is injected and return value it treated as dependency. If result is a promise, it is
2661 * resolved before its value is injected into controller.
2665 * function($http, $stateParams) {
2666 * return $http.get("/api/foos/"+stateParams.fooID);
2670 * @param {string=} stateConfig.url
2673 * A url fragment with optional parameters. When a state is navigated or
2674 * transitioned to, the `$stateParams` service will be populated with any
2675 * parameters that were passed.
2677 * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
2678 * more details on acceptable patterns )
2682 * url: "/users/:userid"
2683 * url: "/books/{bookid:[a-zA-Z_-]}"
2684 * url: "/books/{categoryid:int}"
2685 * url: "/books/{publishername:string}/{categoryid:int}"
2686 * url: "/messages?before&after"
2687 * url: "/messages?{before:date}&{after:date}"
2688 * url: "/messages/:mailboxid?{before:date}&{after:date}"
2691 * @param {object=} stateConfig.views
2692 * <a id='views'></a>
2693 * an optional map<string, object> which defined multiple views, or targets views
2694 * manually/explicitly.
2698 * Targets three named `ui-view`s in the parent state's template
2701 * controller: "headerCtrl",
2702 * templateUrl: "header.html"
2704 * controller: "bodyCtrl",
2705 * templateUrl: "body.html"
2707 * controller: "footCtrl",
2708 * templateUrl: "footer.html"
2712 * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
2715 * controller: "msgHeaderCtrl",
2716 * templateUrl: "msgHeader.html"
2718 * controller: "messagesCtrl",
2719 * templateUrl: "messages.html"
2723 * @param {boolean=} [stateConfig.abstract=false]
2724 * <a id='abstract'></a>
2725 * An abstract state will never be directly activated,
2726 * but can provide inherited properties to its common children states.
2727 * <pre>abstract: true</pre>
2729 * @param {function=} stateConfig.onEnter
2730 * <a id='onEnter'></a>
2732 * Callback function for when a state is entered. Good way
2733 * to trigger an action or dispatch an event, such as opening a dialog.
2734 * If minifying your scripts, make sure to explicitly annotate this function,
2735 * because it won't be automatically annotated by your build tools.
2737 * <pre>onEnter: function(MyService, $stateParams) {
2738 * MyService.foo($stateParams.myParam);
2741 * @param {function=} stateConfig.onExit
2742 * <a id='onExit'></a>
2744 * Callback function for when a state is exited. Good way to
2745 * trigger an action or dispatch an event, such as opening a dialog.
2746 * If minifying your scripts, make sure to explicitly annotate this function,
2747 * because it won't be automatically annotated by your build tools.
2749 * <pre>onExit: function(MyService, $stateParams) {
2750 * MyService.cleanup($stateParams.myParam);
2753 * @param {boolean=} [stateConfig.reloadOnSearch=true]
2754 * <a id='reloadOnSearch'></a>
2756 * If `false`, will not retrigger the same state
2757 * just because a search/query parameter has changed (via $location.search() or $location.hash()).
2758 * Useful for when you'd like to modify $location.search() without triggering a reload.
2759 * <pre>reloadOnSearch: false</pre>
2761 * @param {object=} stateConfig.data
2764 * Arbitrary data object, useful for custom configuration. The parent state's `data` is
2765 * prototypally inherited. In other words, adding a data property to a state adds it to
2766 * the entire subtree via prototypal inheritance.
2769 * requiredRole: 'foo'
2772 * @param {object=} stateConfig.params
2773 * <a id='params'></a>
2775 * A map which optionally configures parameters declared in the `url`, or
2776 * defines additional non-url parameters. For each parameter being
2777 * configured, add a configuration object keyed to the name of the parameter.
2779 * Each parameter configuration object may contain the following properties:
2781 * - ** value ** - {object|function=}: specifies the default value for this
2782 * parameter. This implicitly sets this parameter as optional.
2784 * When UI-Router routes to a state and no value is
2785 * specified for this parameter in the URL or transition, the
2786 * default value will be used instead. If `value` is a function,
2787 * it will be injected and invoked, and the return value used.
2789 * *Note*: `undefined` is treated as "no default value" while `null`
2790 * is treated as "the default value is `null`".
2792 * *Shorthand*: If you only need to configure the default value of the
2793 * parameter, you may use a shorthand syntax. In the **`params`**
2794 * map, instead mapping the param name to a full parameter configuration
2795 * object, simply set map it to the default parameter value, e.g.:
2797 * <pre>// define a parameter's default value
2799 * param1: { value: "defaultValue" }
2801 * // shorthand default values
2803 * param1: "defaultValue",
2804 * param2: "param2Default"
2807 * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
2808 * treated as an array of values. If you specified a Type, the value will be
2809 * treated as an array of the specified Type. Note: query parameter values
2810 * default to a special `"auto"` mode.
2812 * For query parameters in `"auto"` mode, if multiple values for a single parameter
2813 * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
2814 * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
2815 * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
2816 * value (e.g.: `{ foo: '1' }`).
2819 * param1: { array: true }
2822 * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
2823 * the current parameter value is the same as the default value. If `squash` is not set, it uses the
2824 * configured default squash policy.
2825 * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
2827 * There are three squash settings:
2829 * - false: The parameter's default value is not squashed. It is encoded and included in the URL
2830 * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
2831 * by slashes in the state's `url` declaration, then one of those slashes are omitted.
2832 * This can allow for cleaner looking URLs.
2833 * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
2837 * value: "defaultId",
2840 * // squash "defaultValue" to "~"
2843 * value: "defaultValue",
2851 * // Some state name examples
2853 * // stateName can be a single top-level name (must be unique).
2854 * $stateProvider.state("home", {});
2856 * // Or it can be a nested state name. This state is a child of the
2857 * // above "home" state.
2858 * $stateProvider.state("home.newest", {});
2860 * // Nest states as deeply as needed.
2861 * $stateProvider.state("home.newest.abc.xyz.inception", {});
2863 * // state() returns $stateProvider, so you can chain state declarations.
2865 * .state("home", {})
2866 * .state("about", {})
2867 * .state("contacts", {});
2872 function state(name, definition) {
2873 /*jshint validthis: true */
2874 if (isObject(name)) definition = name;
2875 else definition.name = name;
2876 registerState(definition);
2882 * @name ui.router.state.$state
2884 * @requires $rootScope
2886 * @requires ui.router.state.$view
2887 * @requires $injector
2888 * @requires ui.router.util.$resolve
2889 * @requires ui.router.state.$stateParams
2890 * @requires ui.router.router.$urlRouter
2892 * @property {object} params A param object, e.g. {sectionId: section.id)}, that
2893 * you'd like to test against the current active state.
2894 * @property {object} current A reference to the state's config object. However
2895 * you passed it in. Useful for accessing custom data.
2896 * @property {object} transition Currently pending transition. A promise that'll
2897 * resolve or reject.
2900 * `$state` service is responsible for representing states as well as transitioning
2901 * between them. It also provides interfaces to ask for current state or even states
2902 * you're coming from.
2905 $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
2906 function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
2908 var TransitionSuperseded = $q.reject(new Error('transition superseded'));
2909 var TransitionPrevented = $q.reject(new Error('transition prevented'));
2910 var TransitionAborted = $q.reject(new Error('transition aborted'));
2911 var TransitionFailed = $q.reject(new Error('transition failed'));
2913 // Handles the case where a state which is the target of a transition is not found, and the user
2914 // can optionally retry or defer the transition
2915 function handleRedirect(redirect, state, params, options) {
2918 * @name ui.router.state.$state#$stateNotFound
2919 * @eventOf ui.router.state.$state
2920 * @eventType broadcast on root scope
2922 * Fired when a requested state **cannot be found** using the provided state name during transition.
2923 * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
2924 * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
2925 * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
2926 * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
2928 * @param {Object} event Event object.
2929 * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
2930 * @param {State} fromState Current state object.
2931 * @param {Object} fromParams Current state params.
2936 * // somewhere, assume lazy.state has not been defined
2937 * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
2940 * $scope.$on('$stateNotFound',
2941 * function(event, unfoundState, fromState, fromParams){
2942 * console.log(unfoundState.to); // "lazy.state"
2943 * console.log(unfoundState.toParams); // {a:1, b:2}
2944 * console.log(unfoundState.options); // {inherit:false} + default options
2948 var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
2950 if (evt.defaultPrevented) {
2951 $urlRouter.update();
2952 return TransitionAborted;
2959 // Allow the handler to return a promise to defer state lookup retry
2960 if (options.$retry) {
2961 $urlRouter.update();
2962 return TransitionFailed;
2964 var retryTransition = $state.transition = $q.when(evt.retry);
2966 retryTransition.then(function() {
2967 if (retryTransition !== $state.transition) return TransitionSuperseded;
2968 redirect.options.$retry = true;
2969 return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
2971 return TransitionAborted;
2973 $urlRouter.update();
2975 return retryTransition;
2978 root.locals = { resolve: null, globals: { $stateParams: {} } };
2989 * @name ui.router.state.$state#reload
2990 * @methodOf ui.router.state.$state
2993 * A method that force reloads the current state. All resolves are re-resolved,
2994 * controllers reinstantiated, and events re-fired.
2998 * var app angular.module('app', ['ui.router']);
3000 * app.controller('ctrl', function ($scope, $state) {
3001 * $scope.reload = function(){
3007 * `reload()` is just an alias for:
3009 * $state.transitionTo($state.current, $stateParams, {
3010 * reload: true, inherit: false, notify: true
3014 * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
3017 * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
3018 * //and current state is 'contacts.detail.item'
3019 * var app angular.module('app', ['ui.router']);
3021 * app.controller('ctrl', function ($scope, $state) {
3022 * $scope.reload = function(){
3023 * //will reload 'contact.detail' and 'contact.detail.item' states
3024 * $state.reload('contact.detail');
3029 * `reload()` is just an alias for:
3031 * $state.transitionTo($state.current, $stateParams, {
3032 * reload: true, inherit: false, notify: true
3036 * @returns {promise} A promise representing the state of the new transition. See
3037 * {@link ui.router.state.$state#methods_go $state.go}.
3039 $state.reload = function reload(state) {
3040 return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
3045 * @name ui.router.state.$state#go
3046 * @methodOf ui.router.state.$state
3049 * Convenience method for transitioning to a new state. `$state.go` calls
3050 * `$state.transitionTo` internally but automatically sets options to
3051 * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
3052 * This allows you to easily use an absolute or relative to path and specify
3053 * only the parameters you'd like to update (while letting unspecified parameters
3054 * inherit from the currently active ancestor states).
3058 * var app = angular.module('app', ['ui.router']);
3060 * app.controller('ctrl', function ($scope, $state) {
3061 * $scope.changeState = function () {
3062 * $state.go('contact.detail');
3066 * <img src='../ngdoc_assets/StateGoExamples.png'/>
3068 * @param {string} to Absolute state name or relative state path. Some examples:
3070 * - `$state.go('contact.detail')` - will go to the `contact.detail` state
3071 * - `$state.go('^')` - will go to a parent state
3072 * - `$state.go('^.sibling')` - will go to a sibling state
3073 * - `$state.go('.child.grandchild')` - will go to grandchild state
3075 * @param {object=} params A map of the parameters that will be sent to the state,
3076 * will populate $stateParams. Any parameters that are not specified will be inherited from currently
3077 * defined parameters. Only parameters specified in the state definition can be overridden, new
3078 * parameters will be ignored. This allows, for example, going to a sibling state that shares parameters
3079 * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
3080 * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
3081 * will get you all current parameters, etc.
3082 * @param {object=} options Options object. The options are:
3084 * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
3085 * will not. If string, must be `"replace"`, which will update url and also replace last history record.
3086 * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
3087 * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
3088 * defines which state to be relative from.
3089 * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
3090 * - **`reload`** (v0.2.5) - {boolean=false|string|object}, If `true` will force transition even if no state or params
3091 * have changed. It will reload the resolves and views of the current state and parent states.
3092 * If `reload` is a string (or state object), the state object is fetched (by name, or object reference); and \
3093 * the transition reloads the resolves and views for that matched state, and all its children states.
3095 * @returns {promise} A promise representing the state of the new transition.
3097 * Possible success values:
3101 * <br/>Possible rejection values:
3103 * - 'transition superseded' - when a newer transition has been started after this one
3104 * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
3105 * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
3106 * when a `$stateNotFound` `event.retry` promise errors.
3107 * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
3108 * - *resolve error* - when an error has occurred with a `resolve`
3111 $state.go = function go(to, params, options) {
3112 return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
3117 * @name ui.router.state.$state#transitionTo
3118 * @methodOf ui.router.state.$state
3121 * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
3122 * uses `transitionTo` internally. `$state.go` is recommended in most situations.
3126 * var app = angular.module('app', ['ui.router']);
3128 * app.controller('ctrl', function ($scope, $state) {
3129 * $scope.changeState = function () {
3130 * $state.transitionTo('contact.detail');
3135 * @param {string} to State name.
3136 * @param {object=} toParams A map of the parameters that will be sent to the state,
3137 * will populate $stateParams.
3138 * @param {object=} options Options object. The options are:
3140 * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
3141 * will not. If string, must be `"replace"`, which will update url and also replace last history record.
3142 * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
3143 * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
3144 * defines which state to be relative from.
3145 * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
3146 * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params
3147 * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
3148 * use this when you want to force a reload when *everything* is the same, including search params.
3149 * if String, then will reload the state with the name given in reload, and any children.
3150 * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
3152 * @returns {promise} A promise representing the state of the new transition. See
3153 * {@link ui.router.state.$state#methods_go $state.go}.
3155 $state.transitionTo = function transitionTo(to, toParams, options) {
3156 toParams = toParams || {};
3158 location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
3161 var from = $state.$current, fromParams = $state.params, fromPath = from.path;
3162 var evt, toState = findState(to, options.relative);
3164 // Store the hash param for later (since it will be stripped out by various methods)
3165 var hash = toParams['#'];
3167 if (!isDefined(toState)) {
3168 var redirect = { to: to, toParams: toParams, options: options };
3169 var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
3171 if (redirectResult) {
3172 return redirectResult;
3175 // Always retry once if the $stateNotFound was not prevented
3176 // (handles either redirect changed or state lazy-definition)
3178 toParams = redirect.toParams;
3179 options = redirect.options;
3180 toState = findState(to, options.relative);
3182 if (!isDefined(toState)) {
3183 if (!options.relative) throw new Error("No such state '" + to + "'");
3184 throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
3187 if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
3188 if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
3189 if (!toState.params.$$validates(toParams)) return TransitionFailed;
3191 toParams = toState.params.$$values(toParams);
3194 var toPath = to.path;
3196 // Starting from the root of the path, keep all levels that haven't changed
3197 var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
3199 if (!options.reload) {
3200 while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
3201 locals = toLocals[keep] = state.locals;
3203 state = toPath[keep];
3205 } else if (isString(options.reload) || isObject(options.reload)) {
3206 if (isObject(options.reload) && !options.reload.name) {
3207 throw new Error('Invalid reload state object');
3210 var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
3211 if (options.reload && !reloadState) {
3212 throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
3215 while (state && state === fromPath[keep] && state !== reloadState) {
3216 locals = toLocals[keep] = state.locals;
3218 state = toPath[keep];
3222 // If we're going to the same state and all locals are kept, we've got nothing to do.
3223 // But clear 'transition', as we still want to cancel any other pending transitions.
3224 // TODO: We may not want to bump 'transition' if we're called from a location change
3225 // that we've initiated ourselves, because we might accidentally abort a legitimate
3226 // transition initiated from code?
3227 if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
3228 if (hash) toParams['#'] = hash;
3229 $state.params = toParams;
3230 copy($state.params, $stateParams);
3231 copy(filterByKeys(to.params.$$keys(), $stateParams), to.locals.globals.$stateParams);
3232 if (options.location && to.navigable && to.navigable.url) {
3233 $urlRouter.push(to.navigable.url, toParams, {
3234 $$avoidResync: true, replace: options.location === 'replace'
3236 $urlRouter.update(true);
3238 $state.transition = null;
3239 return $q.when($state.current);
3242 // Filter parameters before we pass them to event handlers etc.
3243 toParams = filterByKeys(to.params.$$keys(), toParams || {});
3245 // Re-add the saved hash before we start returning things or broadcasting $stateChangeStart
3246 if (hash) toParams['#'] = hash;
3248 // Broadcast start event and cancel the transition if requested
3249 if (options.notify) {
3252 * @name ui.router.state.$state#$stateChangeStart
3253 * @eventOf ui.router.state.$state
3254 * @eventType broadcast on root scope
3256 * Fired when the state transition **begins**. You can use `event.preventDefault()`
3257 * to prevent the transition from happening and then the transition promise will be
3258 * rejected with a `'transition prevented'` value.
3260 * @param {Object} event Event object.
3261 * @param {State} toState The state being transitioned to.
3262 * @param {Object} toParams The params supplied to the `toState`.
3263 * @param {State} fromState The current state, pre-transition.
3264 * @param {Object} fromParams The params supplied to the `fromState`.
3269 * $rootScope.$on('$stateChangeStart',
3270 * function(event, toState, toParams, fromState, fromParams){
3271 * event.preventDefault();
3272 * // transitionTo() promise will be rejected with
3273 * // a 'transition prevented' error
3277 if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams, options).defaultPrevented) {
3278 $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
3279 //Don't update and resync url if there's been a new transition started. see issue #2238, #600
3280 if ($state.transition == null) $urlRouter.update();
3281 return TransitionPrevented;
3285 // Resolve locals for the remaining states, but don't update any global state just
3286 // yet -- if anything fails to resolve the current state needs to remain untouched.
3287 // We also set up an inheritance chain for the locals here. This allows the view directive
3288 // to quickly look up the correct definition for each view in the current state. Even
3289 // though we create the locals object itself outside resolveState(), it is initially
3290 // empty and gets filled asynchronously. We need to keep track of the promise for the
3291 // (fully resolved) current locals, and pass this down the chain.
3292 var resolved = $q.when(locals);
3294 for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
3295 locals = toLocals[l] = inherit(locals);
3296 resolved = resolveState(state, toParams, state === to, resolved, locals, options);
3299 // Once everything is resolved, we are ready to perform the actual transition
3300 // and return a promise for the new state. We also keep track of what the
3301 // current promise is, so that we can detect overlapping transitions and
3302 // keep only the outcome of the last transition.
3303 var transition = $state.transition = resolved.then(function () {
3304 var l, entering, exiting;
3306 if ($state.transition !== transition) return TransitionSuperseded;
3308 // Exit 'from' states not kept
3309 for (l = fromPath.length - 1; l >= keep; l--) {
3310 exiting = fromPath[l];
3311 if (exiting.self.onExit) {
3312 $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
3314 exiting.locals = null;
3317 // Enter 'to' states not kept
3318 for (l = keep; l < toPath.length; l++) {
3319 entering = toPath[l];
3320 entering.locals = toLocals[l];
3321 if (entering.self.onEnter) {
3322 $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
3326 // Run it again, to catch any transitions in callbacks
3327 if ($state.transition !== transition) return TransitionSuperseded;
3329 // Update globals in $state
3330 $state.$current = to;
3331 $state.current = to.self;
3332 $state.params = toParams;
3333 copy($state.params, $stateParams);
3334 $state.transition = null;
3336 if (options.location && to.navigable) {
3337 $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
3338 $$avoidResync: true, replace: options.location === 'replace'
3342 if (options.notify) {
3345 * @name ui.router.state.$state#$stateChangeSuccess
3346 * @eventOf ui.router.state.$state
3347 * @eventType broadcast on root scope
3349 * Fired once the state transition is **complete**.
3351 * @param {Object} event Event object.
3352 * @param {State} toState The state being transitioned to.
3353 * @param {Object} toParams The params supplied to the `toState`.
3354 * @param {State} fromState The current state, pre-transition.
3355 * @param {Object} fromParams The params supplied to the `fromState`.
3357 $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
3359 $urlRouter.update(true);
3361 return $state.current;
3362 }, function (error) {
3363 if ($state.transition !== transition) return TransitionSuperseded;
3365 $state.transition = null;
3368 * @name ui.router.state.$state#$stateChangeError
3369 * @eventOf ui.router.state.$state
3370 * @eventType broadcast on root scope
3372 * Fired when an **error occurs** during transition. It's important to note that if you
3373 * have any errors in your resolve functions (javascript errors, non-existent services, etc)
3374 * they will not throw traditionally. You must listen for this $stateChangeError event to
3375 * catch **ALL** errors.
3377 * @param {Object} event Event object.
3378 * @param {State} toState The state being transitioned to.
3379 * @param {Object} toParams The params supplied to the `toState`.
3380 * @param {State} fromState The current state, pre-transition.
3381 * @param {Object} fromParams The params supplied to the `fromState`.
3382 * @param {Error} error The resolve error object.
3384 evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
3386 if (!evt.defaultPrevented) {
3387 $urlRouter.update();
3390 return $q.reject(error);
3398 * @name ui.router.state.$state#is
3399 * @methodOf ui.router.state.$state
3402 * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
3403 * but only checks for the full state name. If params is supplied then it will be
3404 * tested for strict equality against the current active params object, so all params
3405 * must match with none missing and no extras.
3409 * $state.$current.name = 'contacts.details.item';
3412 * $state.is('contact.details.item'); // returns true
3413 * $state.is(contactDetailItemStateObject); // returns true
3415 * // relative name (. and ^), typically from a template
3416 * // E.g. from the 'contacts.details' template
3417 * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
3420 * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
3421 * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
3422 * to test against the current active state.
3423 * @param {object=} options An options object. The options are:
3425 * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
3426 * test relative to `options.relative` state (or name).
3428 * @returns {boolean} Returns true if it is the state.
3430 $state.is = function is(stateOrName, params, options) {
3431 options = extend({ relative: $state.$current }, options || {});
3432 var state = findState(stateOrName, options.relative);
3434 if (!isDefined(state)) { return undefined; }
3435 if ($state.$current !== state) { return false; }
3436 return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
3441 * @name ui.router.state.$state#includes
3442 * @methodOf ui.router.state.$state
3445 * A method to determine if the current active state is equal to or is the child of the
3446 * state stateName. If any params are passed then they will be tested for a match as well.
3447 * Not all the parameters need to be passed, just the ones you'd like to test for equality.
3450 * Partial and relative names
3452 * $state.$current.name = 'contacts.details.item';
3454 * // Using partial names
3455 * $state.includes("contacts"); // returns true
3456 * $state.includes("contacts.details"); // returns true
3457 * $state.includes("contacts.details.item"); // returns true
3458 * $state.includes("contacts.list"); // returns false
3459 * $state.includes("about"); // returns false
3461 * // Using relative names (. and ^), typically from a template
3462 * // E.g. from the 'contacts.details' template
3463 * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
3466 * Basic globbing patterns
3468 * $state.$current.name = 'contacts.details.item.url';
3470 * $state.includes("*.details.*.*"); // returns true
3471 * $state.includes("*.details.**"); // returns true
3472 * $state.includes("**.item.**"); // returns true
3473 * $state.includes("*.details.item.url"); // returns true
3474 * $state.includes("*.details.*.url"); // returns true
3475 * $state.includes("*.details.*"); // returns false
3476 * $state.includes("item.**"); // returns false
3479 * @param {string} stateOrName A partial name, relative name, or glob pattern
3480 * to be searched for within the current state name.
3481 * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
3482 * that you'd like to test against the current active state.
3483 * @param {object=} options An options object. The options are:
3485 * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
3486 * .includes will test relative to `options.relative` state (or name).
3488 * @returns {boolean} Returns true if it does include the state
3490 $state.includes = function includes(stateOrName, params, options) {
3491 options = extend({ relative: $state.$current }, options || {});
3492 if (isString(stateOrName) && isGlob(stateOrName)) {
3493 if (!doesStateMatchGlob(stateOrName)) {
3496 stateOrName = $state.$current.name;
3499 var state = findState(stateOrName, options.relative);
3500 if (!isDefined(state)) { return undefined; }
3501 if (!isDefined($state.$current.includes[state.name])) { return false; }
3502 return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
3508 * @name ui.router.state.$state#href
3509 * @methodOf ui.router.state.$state
3512 * A url generation method that returns the compiled url for the given state populated with the given params.
3516 * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
3519 * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
3520 * @param {object=} params An object of parameter values to fill the state's required parameters.
3521 * @param {object=} options Options object. The options are:
3523 * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
3524 * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
3525 * ancestor with a valid url).
3526 * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
3527 * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
3528 * defines which state to be relative from.
3529 * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
3531 * @returns {string} compiled state url
3533 $state.href = function href(stateOrName, params, options) {
3538 relative: $state.$current
3541 var state = findState(stateOrName, options.relative);
3543 if (!isDefined(state)) return null;
3544 if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
3546 var nav = (state && options.lossy) ? state.navigable : state;
3548 if (!nav || nav.url === undefined || nav.url === null) {
3551 return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
3552 absolute: options.absolute
3558 * @name ui.router.state.$state#get
3559 * @methodOf ui.router.state.$state
3562 * Returns the state configuration object for any specific state or all states.
3564 * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
3565 * the requested state. If not provided, returns an array of ALL state configs.
3566 * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
3567 * @returns {Object|Array} State configuration object or array of all objects.
3569 $state.get = function (stateOrName, context) {
3570 if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
3571 var state = findState(stateOrName, context || $state.$current);
3572 return (state && state.self) ? state.self : null;
3575 function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
3576 // Make a restricted $stateParams with only the parameters that apply to this state if
3577 // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
3578 // we also need $stateParams to be available for any $injector calls we make during the
3579 // dependency resolution process.
3580 var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
3581 var locals = { $stateParams: $stateParams };
3583 // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
3584 // We're also including $stateParams in this; that way the parameters are restricted
3585 // to the set that should be visible to the state, and are independent of when we update
3586 // the global $state and $stateParams values.
3587 dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
3588 var promises = [dst.resolve.then(function (globals) {
3589 dst.globals = globals;
3591 if (inherited) promises.push(inherited);
3593 function resolveViews() {
3594 var viewsPromises = [];
3596 // Resolve template and dependencies for all views.
3597 forEach(state.views, function (view, name) {
3598 var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
3599 injectables.$template = [ function () {
3600 return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';
3603 viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
3604 // References to the controller (only instantiated at link time)
3605 if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
3606 var injectLocals = angular.extend({}, injectables, dst.globals);
3607 result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
3609 result.$$controller = view.controller;
3611 // Provide access to the state itself for internal use
3612 result.$$state = state;
3613 result.$$controllerAs = view.controllerAs;
3618 return $q.all(viewsPromises).then(function(){
3623 // Wait for all the promises and then return the activation object
3624 return $q.all(promises).then(resolveViews).then(function (values) {
3632 function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
3633 // Return true if there are no differences in non-search (path/object) params, false if there are differences
3634 function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
3635 // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
3636 function notSearchParam(key) {
3637 return fromAndToState.params[key].location != "search";
3639 var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
3640 var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
3641 var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
3642 return nonQueryParamSet.$$equals(fromParams, toParams);
3645 // If reload was not explicitly requested
3646 // and we're transitioning to the same state we're already in
3647 // and the locals didn't change
3648 // or they changed in a way that doesn't merit reloading
3649 // (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
3650 // Then return true.
3651 if (!options.reload && to === from &&
3652 (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
3658 angular.module('ui.router.state')
3659 .factory('$stateParams', function () { return {}; })
3660 .provider('$state', $StateProvider);
3663 $ViewProvider.$inject = [];
3664 function $ViewProvider() {
3669 * @name ui.router.state.$view
3671 * @requires ui.router.util.$templateFactory
3672 * @requires $rootScope
3677 $get.$inject = ['$rootScope', '$templateFactory'];
3678 function $get( $rootScope, $templateFactory) {
3680 // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
3683 * @name ui.router.state.$view#load
3684 * @methodOf ui.router.state.$view
3688 * @param {string} name name
3689 * @param {object} options option object.
3691 load: function load(name, options) {
3692 var result, defaults = {
3693 template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
3695 options = extend(defaults, options);
3698 result = $templateFactory.fromConfig(options.view, options.params, options.locals);
3706 angular.module('ui.router.state').provider('$view', $ViewProvider);
3710 * @name ui.router.state.$uiViewScrollProvider
3713 * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
3715 function $ViewScrollProvider() {
3717 var useAnchorScroll = false;
3721 * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
3722 * @methodOf ui.router.state.$uiViewScrollProvider
3725 * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
3726 * scrolling based on the url anchor.
3728 this.useAnchorScroll = function () {
3729 useAnchorScroll = true;
3734 * @name ui.router.state.$uiViewScroll
3736 * @requires $anchorScroll
3737 * @requires $timeout
3740 * When called with a jqLite element, it scrolls the element into view (after a
3741 * `$timeout` so the DOM has time to refresh).
3743 * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
3744 * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
3746 this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
3747 if (useAnchorScroll) {
3748 return $anchorScroll;
3751 return function ($element) {
3752 return $timeout(function () {
3753 $element[0].scrollIntoView();
3759 angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
3763 * @name ui.router.state.directive:ui-view
3765 * @requires ui.router.state.$state
3766 * @requires $compile
3767 * @requires $controller
3768 * @requires $injector
3769 * @requires ui.router.state.$uiViewScroll
3770 * @requires $document
3775 * The ui-view directive tells $state where to place your templates.
3777 * @param {string=} name A view name. The name should be unique amongst the other views in the
3778 * same state. You can have views of the same name that live in different states.
3780 * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
3781 * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
3782 * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
3783 * scroll ui-view elements into view when they are populated during a state activation.
3785 * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
3786 * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
3788 * @param {string=} onload Expression to evaluate whenever the view updates.
3791 * A view can be unnamed or named.
3794 * <div ui-view></div>
3797 * <div ui-view="viewName"></div>
3800 * You can only have one unnamed view within any template (or root html). If you are only using a
3801 * single view and it is unnamed then you can populate it like so:
3803 * <div ui-view></div>
3804 * $stateProvider.state("home", {
3805 * template: "<h1>HELLO!</h1>"
3809 * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
3810 * config property, by name, in this case an empty name:
3812 * $stateProvider.state("home", {
3815 * template: "<h1>HELLO!</h1>"
3821 * But typically you'll only use the views property if you name your view or have more than one view
3822 * in the same template. There's not really a compelling reason to name a view if its the only one,
3823 * but you could if you wanted, like so:
3825 * <div ui-view="main"></div>
3828 * $stateProvider.state("home", {
3831 * template: "<h1>HELLO!</h1>"
3837 * Really though, you'll use views to set up multiple views:
3839 * <div ui-view></div>
3840 * <div ui-view="chart"></div>
3841 * <div ui-view="data"></div>
3845 * $stateProvider.state("home", {
3848 * template: "<h1>HELLO!</h1>"
3851 * template: "<chart_thing/>"
3854 * template: "<data_thing/>"
3860 * Examples for `autoscroll`:
3863 * <!-- If autoscroll present with no expression,
3864 * then scroll ui-view into view -->
3865 * <ui-view autoscroll/>
3867 * <!-- If autoscroll present with valid expression,
3868 * then scroll ui-view into view if expression evaluates to true -->
3869 * <ui-view autoscroll='true'/>
3870 * <ui-view autoscroll='false'/>
3871 * <ui-view autoscroll='scopeVariable'/>
3874 $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
3875 function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
3877 function getService() {
3878 return ($injector.has) ? function(service) {
3879 return $injector.has(service) ? $injector.get(service) : null;
3880 } : function(service) {
3882 return $injector.get(service);
3889 var service = getService(),
3890 $animator = service('$animator'),
3891 $animate = service('$animate');
3893 // Returns a set of DOM manipulation functions based on which Angular version
3895 function getRenderer(attrs, scope) {
3896 var statics = function() {
3898 enter: function (element, target, cb) { target.after(element); cb(); },
3899 leave: function (element, cb) { element.remove(); cb(); }
3905 enter: function(element, target, cb) {
3906 if (angular.version.minor > 2) {
3907 $animate.enter(element, null, target).then(cb);
3909 $animate.enter(element, null, target, cb);
3912 leave: function(element, cb) {
3913 if (angular.version.minor > 2) {
3914 $animate.leave(element).then(cb);
3916 $animate.leave(element, cb);
3923 var animate = $animator && $animator(scope, attrs);
3926 enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
3927 leave: function(element, cb) { animate.leave(element); cb(); }
3938 transclude: 'element',
3939 compile: function (tElement, tAttrs, $transclude) {
3940 return function (scope, $element, attrs) {
3941 var previousEl, currentEl, currentScope, latestLocals,
3942 onloadExp = attrs.onload || '',
3943 autoScrollExp = attrs.autoscroll,
3944 renderer = getRenderer(attrs, scope);
3946 scope.$on('$stateChangeSuccess', function() {
3952 function cleanupLastView() {
3953 var _previousEl = previousEl;
3954 var _currentScope = currentScope;
3956 if (_currentScope) {
3957 _currentScope._willBeDestroyed = true;
3960 function cleanOld() {
3962 _previousEl.remove();
3965 if (_currentScope) {
3966 _currentScope.$destroy();
3971 renderer.leave(currentEl, function() {
3976 previousEl = currentEl;
3983 currentScope = null;
3986 function updateView(firstTime) {
3988 name = getUiViewName(scope, attrs, $element, $interpolate),
3989 previousLocals = name && $state.$current && $state.$current.locals[name];
3991 if (!firstTime && previousLocals === latestLocals || scope._willBeDestroyed) return; // nothing to do
3992 newScope = scope.$new();
3993 latestLocals = $state.$current.locals[name];
3997 * @name ui.router.state.directive:ui-view#$viewContentLoading
3998 * @eventOf ui.router.state.directive:ui-view
3999 * @eventType emits on ui-view directive scope
4002 * Fired once the view **begins loading**, *before* the DOM is rendered.
4004 * @param {Object} event Event object.
4005 * @param {string} viewName Name of the view.
4007 newScope.$emit('$viewContentLoading', name);
4009 var clone = $transclude(newScope, function(clone) {
4010 renderer.enter(clone, $element, function onUiViewEnter() {
4012 currentScope.$emit('$viewContentAnimationEnded');
4015 if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
4016 $uiViewScroll(clone);
4023 currentScope = newScope;
4026 * @name ui.router.state.directive:ui-view#$viewContentLoaded
4027 * @eventOf ui.router.state.directive:ui-view
4028 * @eventType emits on ui-view directive scope
4030 * Fired once the view is **loaded**, *after* the DOM is rendered.
4032 * @param {Object} event Event object.
4033 * @param {string} viewName Name of the view.
4035 currentScope.$emit('$viewContentLoaded', name);
4036 currentScope.$eval(onloadExp);
4045 $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
4046 function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
4050 compile: function (tElement) {
4051 var initial = tElement.html();
4052 return function (scope, $element, attrs) {
4053 var current = $state.$current,
4054 name = getUiViewName(scope, attrs, $element, $interpolate),
4055 locals = current && current.locals[name];
4061 $element.data('$uiView', { name: name, state: locals.$$state });
4062 $element.html(locals.$template ? locals.$template : initial);
4064 var link = $compile($element.contents());
4066 if (locals.$$controller) {
4067 locals.$scope = scope;
4068 locals.$element = $element;
4069 var controller = $controller(locals.$$controller, locals);
4070 if (locals.$$controllerAs) {
4071 scope[locals.$$controllerAs] = controller;
4073 $element.data('$ngControllerController', controller);
4074 $element.children().data('$ngControllerController', controller);
4084 * Shared ui-view code for both directives:
4085 * Given scope, element, and its attributes, return the view's name
4087 function getUiViewName(scope, attrs, element, $interpolate) {
4088 var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
4089 var inherited = element.inheritedData('$uiView');
4090 return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
4093 angular.module('ui.router.state').directive('uiView', $ViewDirective);
4094 angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
4096 function parseStateRef(ref, current) {
4097 var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
4098 if (preparsed) ref = current + '(' + preparsed[1] + ')';
4099 parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
4100 if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
4101 return { state: parsed[1], paramExpr: parsed[3] || null };
4104 function stateContext(el) {
4105 var stateData = el.parent().inheritedData('$uiView');
4107 if (stateData && stateData.state && stateData.state.name) {
4108 return stateData.state;
4112 function getTypeInfo(el) {
4113 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
4114 var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
4115 var isForm = el[0].nodeName === "FORM";
4118 attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'),
4119 isAnchor: el.prop("tagName").toUpperCase() === "A",
4124 function clickHook(el, $state, $timeout, type, current) {
4125 return function(e) {
4126 var button = e.which || e.button, target = current();
4128 if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {
4129 // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
4130 var transition = $timeout(function() {
4131 $state.go(target.state, target.params, target.options);
4135 // if the state has no URL, ignore one preventDefault from the <a> directive.
4136 var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1: 0;
4138 e.preventDefault = function() {
4139 if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);
4145 function defaultOpts(el, $state) {
4146 return { relative: stateContext(el) || $state.$current, inherit: true };
4151 * @name ui.router.state.directive:ui-sref
4153 * @requires ui.router.state.$state
4154 * @requires $timeout
4159 * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
4160 * URL, the directive will automatically generate & update the `href` attribute via
4161 * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
4162 * the link will trigger a state transition with optional parameters.
4164 * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
4165 * handled natively by the browser.
4167 * You can also use relative state paths within ui-sref, just like the relative
4168 * paths passed to `$state.go()`. You just need to be aware that the path is relative
4169 * to the state that the link lives in, in other words the state that loaded the
4170 * template containing the link.
4172 * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
4173 * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
4177 * Here's an example of how you'd use ui-sref and how it would compile. If you have the
4178 * following template:
4180 * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
4183 * <li ng-repeat="contact in contacts">
4184 * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
4189 * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
4191 * <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>
4194 * <li ng-repeat="contact in contacts">
4195 * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
4197 * <li ng-repeat="contact in contacts">
4198 * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
4200 * <li ng-repeat="contact in contacts">
4201 * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
4205 * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
4208 * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
4209 * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
4211 $StateRefDirective.$inject = ['$state', '$timeout'];
4212 function $StateRefDirective($state, $timeout) {
4215 require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
4216 link: function(scope, element, attrs, uiSrefActive) {
4217 var ref = parseStateRef(attrs.uiSref, $state.current.name);
4218 var def = { state: ref.state, href: null, params: null };
4219 var type = getTypeInfo(element);
4220 var active = uiSrefActive[1] || uiSrefActive[0];
4222 def.options = extend(defaultOpts(element, $state), attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {});
4224 var update = function(val) {
4225 if (val) def.params = angular.copy(val);
4226 def.href = $state.href(ref.state, def.params, def.options);
4228 if (active) active.$$addStateInfo(ref.state, def.params);
4229 if (def.href !== null) attrs.$set(type.attr, def.href);
4232 if (ref.paramExpr) {
4233 scope.$watch(ref.paramExpr, function(val) { if (val !== def.params) update(val); }, true);
4234 def.params = angular.copy(scope.$eval(ref.paramExpr));
4238 if (!type.clickable) return;
4239 element.bind("click", clickHook(element, $state, $timeout, type, function() { return def; }));
4246 * @name ui.router.state.directive:ui-state
4248 * @requires ui.router.state.uiSref
4253 * Much like ui-sref, but will accept named $scope properties to evaluate for a state definition,
4254 * params and override options.
4256 * @param {string} ui-state 'stateName' can be any valid absolute or relative state
4257 * @param {Object} ui-state-params params to pass to {@link ui.router.state.$state#href $state.href()}
4258 * @param {Object} ui-state-opts options to pass to {@link ui.router.state.$state#go $state.go()}
4260 $StateRefDynamicDirective.$inject = ['$state', '$timeout'];
4261 function $StateRefDynamicDirective($state, $timeout) {
4264 require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
4265 link: function(scope, element, attrs, uiSrefActive) {
4266 var type = getTypeInfo(element);
4267 var active = uiSrefActive[1] || uiSrefActive[0];
4268 var group = [attrs.uiState, attrs.uiStateParams || null, attrs.uiStateOpts || null];
4269 var watch = '[' + group.map(function(val) { return val || 'null'; }).join(', ') + ']';
4270 var def = { state: null, params: null, options: null, href: null };
4272 function runStateRefLink (group) {
4273 def.state = group[0]; def.params = group[1]; def.options = group[2];
4274 def.href = $state.href(def.state, def.params, def.options);
4276 if (active) active.$$addStateInfo(ref.state, def.params);
4277 if (def.href) attrs.$set(type.attr, def.href);
4280 scope.$watch(watch, runStateRefLink, true);
4281 runStateRefLink(scope.$eval(watch));
4283 if (!type.clickable) return;
4284 element.bind("click", clickHook(element, $state, $timeout, type, function() { return def; }));
4292 * @name ui.router.state.directive:ui-sref-active
4294 * @requires ui.router.state.$state
4295 * @requires ui.router.state.$stateParams
4296 * @requires $interpolate
4301 * A directive working alongside ui-sref to add classes to an element when the
4302 * related ui-sref directive's state is active, and removing them when it is inactive.
4303 * The primary use-case is to simplify the special appearance of navigation menus
4304 * relying on `ui-sref`, by having the "active" state's menu button appear different,
4305 * distinguishing it from the inactive menu items.
4307 * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
4308 * ui-sref-active found at the same level or above the ui-sref will be used.
4310 * Will activate when the ui-sref's target state or any child state is active. If you
4311 * need to activate only when the ui-sref target state is active and *not* any of
4312 * it's children, then you will use
4313 * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
4316 * Given the following template:
4319 * <li ui-sref-active="active" class="item">
4320 * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
4326 * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
4327 * the resulting HTML will appear as (note the 'active' class):
4330 * <li ui-sref-active="active" class="item active">
4331 * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
4336 * The class name is interpolated **once** during the directives link time (any further changes to the
4337 * interpolated value are ignored).
4339 * Multiple classes may be specified in a space-separated format:
4342 * <li ui-sref-active='class1 class2 class3'>
4343 * <a ui-sref="app.user">link</a>
4348 * It is also possible to pass ui-sref-active an expression that evaluates
4349 * to an object hash, whose keys represent active class names and whose
4350 * values represent the respective state names/globs.
4351 * ui-sref-active will match if the current active state **includes** any of
4352 * the specified state names/globs, even the abstract ones.
4355 * Given the following template, with "admin" being an abstract state:
4357 * <div ui-sref-active="{'active': 'admin.*'}">
4358 * <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
4362 * When the current state is "admin.roles" the "active" class will be applied
4363 * to both the <div> and <a> elements. It is important to note that the state
4364 * names/globs passed to ui-sref-active shadow the state provided by ui-sref.
4369 * @name ui.router.state.directive:ui-sref-active-eq
4371 * @requires ui.router.state.$state
4372 * @requires ui.router.state.$stateParams
4373 * @requires $interpolate
4378 * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
4379 * when the exact target state used in the `ui-sref` is active; no child states.
4382 $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
4383 function $StateRefActiveDirective($state, $stateParams, $interpolate) {
4386 controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
4387 var states = [], activeClasses = {}, activeEqClass, uiSrefActive;
4389 // There probably isn't much point in $observing this
4390 // uiSrefActive and uiSrefActiveEq share the same directive object with some
4391 // slight difference in logic routing
4392 activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
4395 uiSrefActive = $scope.$eval($attrs.uiSrefActive);
4397 // Do nothing. uiSrefActive is not a valid expression.
4398 // Fall back to using $interpolate below
4400 uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
4401 if (isObject(uiSrefActive)) {
4402 forEach(uiSrefActive, function(stateOrName, activeClass) {
4403 if (isString(stateOrName)) {
4404 var ref = parseStateRef(stateOrName, $state.current.name);
4405 addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
4410 // Allow uiSref to communicate with uiSrefActive[Equals]
4411 this.$$addStateInfo = function (newState, newParams) {
4412 // we already got an explicit state provided by ui-sref-active, so we
4413 // shadow the one that comes from ui-sref
4414 if (isObject(uiSrefActive) && states.length > 0) {
4417 addState(newState, newParams, uiSrefActive);
4421 $scope.$on('$stateChangeSuccess', update);
4423 function addState(stateName, stateParams, activeClass) {
4424 var state = $state.get(stateName, stateContext($element));
4425 var stateHash = createStateHash(stateName, stateParams);
4428 state: state || { name: stateName },
4429 params: stateParams,
4433 activeClasses[stateHash] = activeClass;
4437 * @param {string} state
4438 * @param {Object|string} [params]
4441 function createStateHash(state, params) {
4442 if (!isString(state)) {
4443 throw new Error('state should be a string');
4445 if (isObject(params)) {
4446 return state + toJson(params);
4448 params = $scope.$eval(params);
4449 if (isObject(params)) {
4450 return state + toJson(params);
4455 // Update route state
4457 for (var i = 0; i < states.length; i++) {
4458 if (anyMatch(states[i].state, states[i].params)) {
4459 addClass($element, activeClasses[states[i].hash]);
4461 removeClass($element, activeClasses[states[i].hash]);
4464 if (exactMatch(states[i].state, states[i].params)) {
4465 addClass($element, activeEqClass);
4467 removeClass($element, activeEqClass);
4472 function addClass(el, className) { $timeout(function () { el.addClass(className); }); }
4473 function removeClass(el, className) { el.removeClass(className); }
4474 function anyMatch(state, params) { return $state.includes(state.name, params); }
4475 function exactMatch(state, params) { return $state.is(state.name, params); }
4482 angular.module('ui.router.state')
4483 .directive('uiSref', $StateRefDirective)
4484 .directive('uiSrefActive', $StateRefActiveDirective)
4485 .directive('uiSrefActiveEq', $StateRefActiveDirective)
4486 .directive('uiState', $StateRefDynamicDirective);
4490 * @name ui.router.state.filter:isState
4492 * @requires ui.router.state.$state
4495 * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
4497 $IsStateFilter.$inject = ['$state'];
4498 function $IsStateFilter($state) {
4499 var isFilter = function (state, params) {
4500 return $state.is(state, params);
4502 isFilter.$stateful = true;
4508 * @name ui.router.state.filter:includedByState
4510 * @requires ui.router.state.$state
4513 * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
4515 $IncludedByStateFilter.$inject = ['$state'];
4516 function $IncludedByStateFilter($state) {
4517 var includesFilter = function (state, params, options) {
4518 return $state.includes(state, params, options);
4520 includesFilter.$stateful = true;
4521 return includesFilter;
4524 angular.module('ui.router.state')
4525 .filter('isState', $IsStateFilter)
4526 .filter('includedByState', $IncludedByStateFilter);
4527 })(window, window.angular);