Implemented URL query parsing for initial token /opa/?token=abcde
[src/app-framework-demo.git] / afb-client / bower_components / angular-ui-router / src / state.js
1 /**
2  * @ngdoc object
3  * @name ui.router.state.$stateProvider
4  *
5  * @requires ui.router.router.$urlRouterProvider
6  * @requires ui.router.util.$urlMatcherFactoryProvider
7  *
8  * @description
9  * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
10  * on state.
11  *
12  * A state corresponds to a "place" in the application in terms of the overall UI and
13  * navigation. A state describes (via the controller / template / view properties) what
14  * the UI looks like and does at that place.
15  *
16  * States often have things in common, and the primary way of factoring out these
17  * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
18  * nested states.
19  *
20  * The `$stateProvider` provides interfaces to declare these states for your app.
21  */
22 $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
23 function $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {
24
25   var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
26
27   // Builds state properties from definition passed to registerState()
28   var stateBuilder = {
29
30     // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
31     // state.children = [];
32     // if (parent) parent.children.push(state);
33     parent: function(state) {
34       if (isDefined(state.parent) && state.parent) return findState(state.parent);
35       // regex matches any valid composite state name
36       // would match "contact.list" but not "contacts"
37       var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
38       return compositeName ? findState(compositeName[1]) : root;
39     },
40
41     // inherit 'data' from parent and override by own values (if any)
42     data: function(state) {
43       if (state.parent && state.parent.data) {
44         state.data = state.self.data = inherit(state.parent.data, state.data);
45       }
46       return state.data;
47     },
48
49     // Build a URLMatcher if necessary, either via a relative or absolute URL
50     url: function(state) {
51       var url = state.url, config = { params: state.params || {} };
52
53       if (isString(url)) {
54         if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
55         return (state.parent.navigable || root).url.concat(url, config);
56       }
57
58       if (!url || $urlMatcherFactory.isMatcher(url)) return url;
59       throw new Error("Invalid url '" + url + "' in state '" + state + "'");
60     },
61
62     // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
63     navigable: function(state) {
64       return state.url ? state : (state.parent ? state.parent.navigable : null);
65     },
66
67     // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
68     ownParams: function(state) {
69       var params = state.url && state.url.params || new $$UMFP.ParamSet();
70       forEach(state.params || {}, function(config, id) {
71         if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
72       });
73       return params;
74     },
75
76     // Derive parameters for this state and ensure they're a super-set of parent's parameters
77     params: function(state) {
78       var ownParams = pick(state.ownParams, state.ownParams.$$keys());
79       return state.parent && state.parent.params ? extend(state.parent.params.$$new(), ownParams) : new $$UMFP.ParamSet();
80     },
81
82     // If there is no explicit multi-view configuration, make one up so we don't have
83     // to handle both cases in the view directive later. Note that having an explicit
84     // 'views' property will mean the default unnamed view properties are ignored. This
85     // is also a good time to resolve view names to absolute names, so everything is a
86     // straight lookup at link time.
87     views: function(state) {
88       var views = {};
89
90       forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
91         if (name.indexOf('@') < 0) name += '@' + state.parent.name;
92         views[name] = view;
93       });
94       return views;
95     },
96
97     // Keep a full path from the root down to this state as this is needed for state activation.
98     path: function(state) {
99       return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
100     },
101
102     // Speed up $state.contains() as it's used a lot
103     includes: function(state) {
104       var includes = state.parent ? extend({}, state.parent.includes) : {};
105       includes[state.name] = true;
106       return includes;
107     },
108
109     $delegates: {}
110   };
111
112   function isRelative(stateName) {
113     return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
114   }
115
116   function findState(stateOrName, base) {
117     if (!stateOrName) return undefined;
118
119     var isStr = isString(stateOrName),
120         name  = isStr ? stateOrName : stateOrName.name,
121         path  = isRelative(name);
122
123     if (path) {
124       if (!base) throw new Error("No reference point given for path '"  + name + "'");
125       base = findState(base);
126       
127       var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
128
129       for (; i < pathLength; i++) {
130         if (rel[i] === "" && i === 0) {
131           current = base;
132           continue;
133         }
134         if (rel[i] === "^") {
135           if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
136           current = current.parent;
137           continue;
138         }
139         break;
140       }
141       rel = rel.slice(i).join(".");
142       name = current.name + (current.name && rel ? "." : "") + rel;
143     }
144     var state = states[name];
145
146     if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
147       return state;
148     }
149     return undefined;
150   }
151
152   function queueState(parentName, state) {
153     if (!queue[parentName]) {
154       queue[parentName] = [];
155     }
156     queue[parentName].push(state);
157   }
158
159   function flushQueuedChildren(parentName) {
160     var queued = queue[parentName] || [];
161     while(queued.length) {
162       registerState(queued.shift());
163     }
164   }
165
166   function registerState(state) {
167     // Wrap a new object around the state so we can store our private details easily.
168     state = inherit(state, {
169       self: state,
170       resolve: state.resolve || {},
171       toString: function() { return this.name; }
172     });
173
174     var name = state.name;
175     if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
176     if (states.hasOwnProperty(name)) throw new Error("State '" + name + "' is already defined");
177
178     // Get parent name
179     var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
180         : (isString(state.parent)) ? state.parent
181         : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
182         : '';
183
184     // If parent is not registered yet, add state to queue and register later
185     if (parentName && !states[parentName]) {
186       return queueState(parentName, state.self);
187     }
188
189     for (var key in stateBuilder) {
190       if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
191     }
192     states[name] = state;
193
194     // Register the state in the global state list and with $urlRouter if necessary.
195     if (!state[abstractKey] && state.url) {
196       $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
197         if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
198           $state.transitionTo(state, $match, { inherit: true, location: false });
199         }
200       }]);
201     }
202
203     // Register any queued children
204     flushQueuedChildren(name);
205
206     return state;
207   }
208
209   // Checks text to see if it looks like a glob.
210   function isGlob (text) {
211     return text.indexOf('*') > -1;
212   }
213
214   // Returns true if glob matches current $state name.
215   function doesStateMatchGlob (glob) {
216     var globSegments = glob.split('.'),
217         segments = $state.$current.name.split('.');
218
219     //match single stars
220     for (var i = 0, l = globSegments.length; i < l; i++) {
221       if (globSegments[i] === '*') {
222         segments[i] = '*';
223       }
224     }
225
226     //match greedy starts
227     if (globSegments[0] === '**') {
228        segments = segments.slice(indexOf(segments, globSegments[1]));
229        segments.unshift('**');
230     }
231     //match greedy ends
232     if (globSegments[globSegments.length - 1] === '**') {
233        segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
234        segments.push('**');
235     }
236
237     if (globSegments.length != segments.length) {
238       return false;
239     }
240
241     return segments.join('') === globSegments.join('');
242   }
243
244
245   // Implicit root state that is always active
246   root = registerState({
247     name: '',
248     url: '^',
249     views: null,
250     'abstract': true
251   });
252   root.navigable = null;
253
254
255   /**
256    * @ngdoc function
257    * @name ui.router.state.$stateProvider#decorator
258    * @methodOf ui.router.state.$stateProvider
259    *
260    * @description
261    * Allows you to extend (carefully) or override (at your own peril) the 
262    * `stateBuilder` object used internally by `$stateProvider`. This can be used 
263    * to add custom functionality to ui-router, for example inferring templateUrl 
264    * based on the state name.
265    *
266    * When passing only a name, it returns the current (original or decorated) builder
267    * function that matches `name`.
268    *
269    * The builder functions that can be decorated are listed below. Though not all
270    * necessarily have a good use case for decoration, that is up to you to decide.
271    *
272    * In addition, users can attach custom decorators, which will generate new 
273    * properties within the state's internal definition. There is currently no clear 
274    * use-case for this beyond accessing internal states (i.e. $state.$current), 
275    * however, expect this to become increasingly relevant as we introduce additional 
276    * meta-programming features.
277    *
278    * **Warning**: Decorators should not be interdependent because the order of 
279    * execution of the builder functions in non-deterministic. Builder functions 
280    * should only be dependent on the state definition object and super function.
281    *
282    *
283    * Existing builder functions and current return values:
284    *
285    * - **parent** `{object}` - returns the parent state object.
286    * - **data** `{object}` - returns state data, including any inherited data that is not
287    *   overridden by own values (if any).
288    * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
289    *   or `null`.
290    * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is 
291    *   navigable).
292    * - **params** `{object}` - returns an array of state params that are ensured to 
293    *   be a super-set of parent's params.
294    * - **views** `{object}` - returns a views object where each key is an absolute view 
295    *   name (i.e. "viewName@stateName") and each value is the config object 
296    *   (template, controller) for the view. Even when you don't use the views object 
297    *   explicitly on a state config, one is still created for you internally.
298    *   So by decorating this builder function you have access to decorating template 
299    *   and controller properties.
300    * - **ownParams** `{object}` - returns an array of params that belong to the state, 
301    *   not including any params defined by ancestor states.
302    * - **path** `{string}` - returns the full path from the root down to this state. 
303    *   Needed for state activation.
304    * - **includes** `{object}` - returns an object that includes every state that 
305    *   would pass a `$state.includes()` test.
306    *
307    * @example
308    * <pre>
309    * // Override the internal 'views' builder with a function that takes the state
310    * // definition, and a reference to the internal function being overridden:
311    * $stateProvider.decorator('views', function (state, parent) {
312    *   var result = {},
313    *       views = parent(state);
314    *
315    *   angular.forEach(views, function (config, name) {
316    *     var autoName = (state.name + '.' + name).replace('.', '/');
317    *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
318    *     result[name] = config;
319    *   });
320    *   return result;
321    * });
322    *
323    * $stateProvider.state('home', {
324    *   views: {
325    *     'contact.list': { controller: 'ListController' },
326    *     'contact.item': { controller: 'ItemController' }
327    *   }
328    * });
329    *
330    * // ...
331    *
332    * $state.go('home');
333    * // Auto-populates list and item views with /partials/home/contact/list.html,
334    * // and /partials/home/contact/item.html, respectively.
335    * </pre>
336    *
337    * @param {string} name The name of the builder function to decorate. 
338    * @param {object} func A function that is responsible for decorating the original 
339    * builder function. The function receives two parameters:
340    *
341    *   - `{object}` - state - The state config object.
342    *   - `{object}` - super - The original builder function.
343    *
344    * @return {object} $stateProvider - $stateProvider instance
345    */
346   this.decorator = decorator;
347   function decorator(name, func) {
348     /*jshint validthis: true */
349     if (isString(name) && !isDefined(func)) {
350       return stateBuilder[name];
351     }
352     if (!isFunction(func) || !isString(name)) {
353       return this;
354     }
355     if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
356       stateBuilder.$delegates[name] = stateBuilder[name];
357     }
358     stateBuilder[name] = func;
359     return this;
360   }
361
362   /**
363    * @ngdoc function
364    * @name ui.router.state.$stateProvider#state
365    * @methodOf ui.router.state.$stateProvider
366    *
367    * @description
368    * Registers a state configuration under a given state name. The stateConfig object
369    * has the following acceptable properties.
370    *
371    * @param {string} name A unique state name, e.g. "home", "about", "contacts".
372    * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
373    * @param {object} stateConfig State configuration object.
374    * @param {string|function=} stateConfig.template
375    * <a id='template'></a>
376    *   html template as a string or a function that returns
377    *   an html template as a string which should be used by the uiView directives. This property 
378    *   takes precedence over templateUrl.
379    *   
380    *   If `template` is a function, it will be called with the following parameters:
381    *
382    *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
383    *     applying the current state
384    *
385    * <pre>template:
386    *   "<h1>inline template definition</h1>" +
387    *   "<div ui-view></div>"</pre>
388    * <pre>template: function(params) {
389    *       return "<h1>generated template</h1>"; }</pre>
390    * </div>
391    *
392    * @param {string|function=} stateConfig.templateUrl
393    * <a id='templateUrl'></a>
394    *
395    *   path or function that returns a path to an html
396    *   template that should be used by uiView.
397    *   
398    *   If `templateUrl` is a function, it will be called with the following parameters:
399    *
400    *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by 
401    *     applying the current state
402    *
403    * <pre>templateUrl: "home.html"</pre>
404    * <pre>templateUrl: function(params) {
405    *     return myTemplates[params.pageId]; }</pre>
406    *
407    * @param {function=} stateConfig.templateProvider
408    * <a id='templateProvider'></a>
409    *    Provider function that returns HTML content string.
410    * <pre> templateProvider:
411    *       function(MyTemplateService, params) {
412    *         return MyTemplateService.getTemplate(params.pageId);
413    *       }</pre>
414    *
415    * @param {string|function=} stateConfig.controller
416    * <a id='controller'></a>
417    *
418    *  Controller fn that should be associated with newly
419    *   related scope or the name of a registered controller if passed as a string.
420    *   Optionally, the ControllerAs may be declared here.
421    * <pre>controller: "MyRegisteredController"</pre>
422    * <pre>controller:
423    *     "MyRegisteredController as fooCtrl"}</pre>
424    * <pre>controller: function($scope, MyService) {
425    *     $scope.data = MyService.getData(); }</pre>
426    *
427    * @param {function=} stateConfig.controllerProvider
428    * <a id='controllerProvider'></a>
429    *
430    * Injectable provider function that returns the actual controller or string.
431    * <pre>controllerProvider:
432    *   function(MyResolveData) {
433    *     if (MyResolveData.foo)
434    *       return "FooCtrl"
435    *     else if (MyResolveData.bar)
436    *       return "BarCtrl";
437    *     else return function($scope) {
438    *       $scope.baz = "Qux";
439    *     }
440    *   }</pre>
441    *
442    * @param {string=} stateConfig.controllerAs
443    * <a id='controllerAs'></a>
444    * 
445    * A controller alias name. If present the controller will be
446    *   published to scope under the controllerAs name.
447    * <pre>controllerAs: "myCtrl"</pre>
448    *
449    * @param {string|object=} stateConfig.parent
450    * <a id='parent'></a>
451    * Optionally specifies the parent state of this state.
452    *
453    * <pre>parent: 'parentState'</pre>
454    * <pre>parent: parentState // JS variable</pre>
455    *
456    * @param {object=} stateConfig.resolve
457    * <a id='resolve'></a>
458    *
459    * An optional map&lt;string, function&gt; of dependencies which
460    *   should be injected into the controller. If any of these dependencies are promises, 
461    *   the router will wait for them all to be resolved before the controller is instantiated.
462    *   If all the promises are resolved successfully, the $stateChangeSuccess event is fired
463    *   and the values of the resolved promises are injected into any controllers that reference them.
464    *   If any  of the promises are rejected the $stateChangeError event is fired.
465    *
466    *   The map object is:
467    *   
468    *   - key - {string}: name of dependency to be injected into controller
469    *   - factory - {string|function}: If string then it is alias for service. Otherwise if function, 
470    *     it is injected and return value it treated as dependency. If result is a promise, it is 
471    *     resolved before its value is injected into controller.
472    *
473    * <pre>resolve: {
474    *     myResolve1:
475    *       function($http, $stateParams) {
476    *         return $http.get("/api/foos/"+stateParams.fooID);
477    *       }
478    *     }</pre>
479    *
480    * @param {string=} stateConfig.url
481    * <a id='url'></a>
482    *
483    *   A url fragment with optional parameters. When a state is navigated or
484    *   transitioned to, the `$stateParams` service will be populated with any 
485    *   parameters that were passed.
486    *
487    *   (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
488    *   more details on acceptable patterns )
489    *
490    * examples:
491    * <pre>url: "/home"
492    * url: "/users/:userid"
493    * url: "/books/{bookid:[a-zA-Z_-]}"
494    * url: "/books/{categoryid:int}"
495    * url: "/books/{publishername:string}/{categoryid:int}"
496    * url: "/messages?before&after"
497    * url: "/messages?{before:date}&{after:date}"
498    * url: "/messages/:mailboxid?{before:date}&{after:date}"
499    * </pre>
500    *
501    * @param {object=} stateConfig.views
502    * <a id='views'></a>
503    * an optional map&lt;string, object&gt; which defined multiple views, or targets views
504    * manually/explicitly.
505    *
506    * Examples:
507    *
508    * Targets three named `ui-view`s in the parent state's template
509    * <pre>views: {
510    *     header: {
511    *       controller: "headerCtrl",
512    *       templateUrl: "header.html"
513    *     }, body: {
514    *       controller: "bodyCtrl",
515    *       templateUrl: "body.html"
516    *     }, footer: {
517    *       controller: "footCtrl",
518    *       templateUrl: "footer.html"
519    *     }
520    *   }</pre>
521    *
522    * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
523    * <pre>views: {
524    *     'header@top': {
525    *       controller: "msgHeaderCtrl",
526    *       templateUrl: "msgHeader.html"
527    *     }, 'body': {
528    *       controller: "messagesCtrl",
529    *       templateUrl: "messages.html"
530    *     }
531    *   }</pre>
532    *
533    * @param {boolean=} [stateConfig.abstract=false]
534    * <a id='abstract'></a>
535    * An abstract state will never be directly activated,
536    *   but can provide inherited properties to its common children states.
537    * <pre>abstract: true</pre>
538    *
539    * @param {function=} stateConfig.onEnter
540    * <a id='onEnter'></a>
541    *
542    * Callback function for when a state is entered. Good way
543    *   to trigger an action or dispatch an event, such as opening a dialog.
544    * If minifying your scripts, make sure to explicitly annotate this function,
545    * because it won't be automatically annotated by your build tools.
546    *
547    * <pre>onEnter: function(MyService, $stateParams) {
548    *     MyService.foo($stateParams.myParam);
549    * }</pre>
550    *
551    * @param {function=} stateConfig.onExit
552    * <a id='onExit'></a>
553    *
554    * Callback function for when a state is exited. Good way to
555    *   trigger an action or dispatch an event, such as opening a dialog.
556    * If minifying your scripts, make sure to explicitly annotate this function,
557    * because it won't be automatically annotated by your build tools.
558    *
559    * <pre>onExit: function(MyService, $stateParams) {
560    *     MyService.cleanup($stateParams.myParam);
561    * }</pre>
562    *
563    * @param {boolean=} [stateConfig.reloadOnSearch=true]
564    * <a id='reloadOnSearch'></a>
565    *
566    * If `false`, will not retrigger the same state
567    *   just because a search/query parameter has changed (via $location.search() or $location.hash()). 
568    *   Useful for when you'd like to modify $location.search() without triggering a reload.
569    * <pre>reloadOnSearch: false</pre>
570    *
571    * @param {object=} stateConfig.data
572    * <a id='data'></a>
573    *
574    * Arbitrary data object, useful for custom configuration.  The parent state's `data` is
575    *   prototypally inherited.  In other words, adding a data property to a state adds it to
576    *   the entire subtree via prototypal inheritance.
577    *
578    * <pre>data: {
579    *     requiredRole: 'foo'
580    * } </pre>
581    *
582    * @param {object=} stateConfig.params
583    * <a id='params'></a>
584    *
585    * A map which optionally configures parameters declared in the `url`, or
586    *   defines additional non-url parameters.  For each parameter being
587    *   configured, add a configuration object keyed to the name of the parameter.
588    *
589    *   Each parameter configuration object may contain the following properties:
590    *
591    *   - ** value ** - {object|function=}: specifies the default value for this
592    *     parameter.  This implicitly sets this parameter as optional.
593    *
594    *     When UI-Router routes to a state and no value is
595    *     specified for this parameter in the URL or transition, the
596    *     default value will be used instead.  If `value` is a function,
597    *     it will be injected and invoked, and the return value used.
598    *
599    *     *Note*: `undefined` is treated as "no default value" while `null`
600    *     is treated as "the default value is `null`".
601    *
602    *     *Shorthand*: If you only need to configure the default value of the
603    *     parameter, you may use a shorthand syntax.   In the **`params`**
604    *     map, instead mapping the param name to a full parameter configuration
605    *     object, simply set map it to the default parameter value, e.g.:
606    *
607    * <pre>// define a parameter's default value
608    * params: {
609    *     param1: { value: "defaultValue" }
610    * }
611    * // shorthand default values
612    * params: {
613    *     param1: "defaultValue",
614    *     param2: "param2Default"
615    * }</pre>
616    *
617    *   - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
618    *     treated as an array of values.  If you specified a Type, the value will be
619    *     treated as an array of the specified Type.  Note: query parameter values
620    *     default to a special `"auto"` mode.
621    *
622    *     For query parameters in `"auto"` mode, if multiple  values for a single parameter
623    *     are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
624    *     are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`).  However, if
625    *     only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
626    *     value (e.g.: `{ foo: '1' }`).
627    *
628    * <pre>params: {
629    *     param1: { array: true }
630    * }</pre>
631    *
632    *   - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
633    *     the current parameter value is the same as the default value. If `squash` is not set, it uses the
634    *     configured default squash policy.
635    *     (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
636    *
637    *   There are three squash settings:
638    *
639    *     - false: The parameter's default value is not squashed.  It is encoded and included in the URL
640    *     - true: The parameter's default value is omitted from the URL.  If the parameter is preceeded and followed
641    *       by slashes in the state's `url` declaration, then one of those slashes are omitted.
642    *       This can allow for cleaner looking URLs.
643    *     - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of  your choice.
644    *
645    * <pre>params: {
646    *     param1: {
647    *       value: "defaultId",
648    *       squash: true
649    * } }
650    * // squash "defaultValue" to "~"
651    * params: {
652    *     param1: {
653    *       value: "defaultValue",
654    *       squash: "~"
655    * } }
656    * </pre>
657    *
658    *
659    * @example
660    * <pre>
661    * // Some state name examples
662    *
663    * // stateName can be a single top-level name (must be unique).
664    * $stateProvider.state("home", {});
665    *
666    * // Or it can be a nested state name. This state is a child of the
667    * // above "home" state.
668    * $stateProvider.state("home.newest", {});
669    *
670    * // Nest states as deeply as needed.
671    * $stateProvider.state("home.newest.abc.xyz.inception", {});
672    *
673    * // state() returns $stateProvider, so you can chain state declarations.
674    * $stateProvider
675    *   .state("home", {})
676    *   .state("about", {})
677    *   .state("contacts", {});
678    * </pre>
679    *
680    */
681   this.state = state;
682   function state(name, definition) {
683     /*jshint validthis: true */
684     if (isObject(name)) definition = name;
685     else definition.name = name;
686     registerState(definition);
687     return this;
688   }
689
690   /**
691    * @ngdoc object
692    * @name ui.router.state.$state
693    *
694    * @requires $rootScope
695    * @requires $q
696    * @requires ui.router.state.$view
697    * @requires $injector
698    * @requires ui.router.util.$resolve
699    * @requires ui.router.state.$stateParams
700    * @requires ui.router.router.$urlRouter
701    *
702    * @property {object} params A param object, e.g. {sectionId: section.id)}, that 
703    * you'd like to test against the current active state.
704    * @property {object} current A reference to the state's config object. However 
705    * you passed it in. Useful for accessing custom data.
706    * @property {object} transition Currently pending transition. A promise that'll 
707    * resolve or reject.
708    *
709    * @description
710    * `$state` service is responsible for representing states as well as transitioning
711    * between them. It also provides interfaces to ask for current state or even states
712    * you're coming from.
713    */
714   this.$get = $get;
715   $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
716   function $get(   $rootScope,   $q,   $view,   $injector,   $resolve,   $stateParams,   $urlRouter,   $location,   $urlMatcherFactory) {
717
718     var TransitionSuperseded = $q.reject(new Error('transition superseded'));
719     var TransitionPrevented = $q.reject(new Error('transition prevented'));
720     var TransitionAborted = $q.reject(new Error('transition aborted'));
721     var TransitionFailed = $q.reject(new Error('transition failed'));
722
723     // Handles the case where a state which is the target of a transition is not found, and the user
724     // can optionally retry or defer the transition
725     function handleRedirect(redirect, state, params, options) {
726       /**
727        * @ngdoc event
728        * @name ui.router.state.$state#$stateNotFound
729        * @eventOf ui.router.state.$state
730        * @eventType broadcast on root scope
731        * @description
732        * Fired when a requested state **cannot be found** using the provided state name during transition.
733        * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
734        * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
735        * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
736        * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
737        *
738        * @param {Object} event Event object.
739        * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
740        * @param {State} fromState Current state object.
741        * @param {Object} fromParams Current state params.
742        *
743        * @example
744        *
745        * <pre>
746        * // somewhere, assume lazy.state has not been defined
747        * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
748        *
749        * // somewhere else
750        * $scope.$on('$stateNotFound',
751        * function(event, unfoundState, fromState, fromParams){
752        *     console.log(unfoundState.to); // "lazy.state"
753        *     console.log(unfoundState.toParams); // {a:1, b:2}
754        *     console.log(unfoundState.options); // {inherit:false} + default options
755        * })
756        * </pre>
757        */
758       var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
759
760       if (evt.defaultPrevented) {
761         $urlRouter.update();
762         return TransitionAborted;
763       }
764
765       if (!evt.retry) {
766         return null;
767       }
768
769       // Allow the handler to return a promise to defer state lookup retry
770       if (options.$retry) {
771         $urlRouter.update();
772         return TransitionFailed;
773       }
774       var retryTransition = $state.transition = $q.when(evt.retry);
775
776       retryTransition.then(function() {
777         if (retryTransition !== $state.transition) return TransitionSuperseded;
778         redirect.options.$retry = true;
779         return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
780       }, function() {
781         return TransitionAborted;
782       });
783       $urlRouter.update();
784
785       return retryTransition;
786     }
787
788     root.locals = { resolve: null, globals: { $stateParams: {} } };
789
790     $state = {
791       params: {},
792       current: root.self,
793       $current: root,
794       transition: null
795     };
796
797     /**
798      * @ngdoc function
799      * @name ui.router.state.$state#reload
800      * @methodOf ui.router.state.$state
801      *
802      * @description
803      * A method that force reloads the current state. All resolves are re-resolved,
804      * controllers reinstantiated, and events re-fired.
805      *
806      * @example
807      * <pre>
808      * var app angular.module('app', ['ui.router']);
809      *
810      * app.controller('ctrl', function ($scope, $state) {
811      *   $scope.reload = function(){
812      *     $state.reload();
813      *   }
814      * });
815      * </pre>
816      *
817      * `reload()` is just an alias for:
818      * <pre>
819      * $state.transitionTo($state.current, $stateParams, { 
820      *   reload: true, inherit: false, notify: true
821      * });
822      * </pre>
823      *
824      * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
825      * @example
826      * <pre>
827      * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item' 
828      * //and current state is 'contacts.detail.item'
829      * var app angular.module('app', ['ui.router']);
830      *
831      * app.controller('ctrl', function ($scope, $state) {
832      *   $scope.reload = function(){
833      *     //will reload 'contact.detail' and 'contact.detail.item' states
834      *     $state.reload('contact.detail');
835      *   }
836      * });
837      * </pre>
838      *
839      * `reload()` is just an alias for:
840      * <pre>
841      * $state.transitionTo($state.current, $stateParams, { 
842      *   reload: true, inherit: false, notify: true
843      * });
844      * </pre>
845
846      * @returns {promise} A promise representing the state of the new transition. See
847      * {@link ui.router.state.$state#methods_go $state.go}.
848      */
849     $state.reload = function reload(state) {
850       return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
851     };
852
853     /**
854      * @ngdoc function
855      * @name ui.router.state.$state#go
856      * @methodOf ui.router.state.$state
857      *
858      * @description
859      * Convenience method for transitioning to a new state. `$state.go` calls 
860      * `$state.transitionTo` internally but automatically sets options to 
861      * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. 
862      * This allows you to easily use an absolute or relative to path and specify 
863      * only the parameters you'd like to update (while letting unspecified parameters 
864      * inherit from the currently active ancestor states).
865      *
866      * @example
867      * <pre>
868      * var app = angular.module('app', ['ui.router']);
869      *
870      * app.controller('ctrl', function ($scope, $state) {
871      *   $scope.changeState = function () {
872      *     $state.go('contact.detail');
873      *   };
874      * });
875      * </pre>
876      * <img src='../ngdoc_assets/StateGoExamples.png'/>
877      *
878      * @param {string} to Absolute state name or relative state path. Some examples:
879      *
880      * - `$state.go('contact.detail')` - will go to the `contact.detail` state
881      * - `$state.go('^')` - will go to a parent state
882      * - `$state.go('^.sibling')` - will go to a sibling state
883      * - `$state.go('.child.grandchild')` - will go to grandchild state
884      *
885      * @param {object=} params A map of the parameters that will be sent to the state, 
886      * will populate $stateParams. Any parameters that are not specified will be inherited from currently 
887      * defined parameters. Only parameters specified in the state definition can be overridden, new 
888      * parameters will be ignored. This allows, for example, going to a sibling state that shares parameters
889      * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
890      * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
891      * will get you all current parameters, etc.
892      * @param {object=} options Options object. The options are:
893      *
894      * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
895      *    will not. If string, must be `"replace"`, which will update url and also replace last history record.
896      * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
897      * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), 
898      *    defines which state to be relative from.
899      * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
900      * - **`reload`** (v0.2.5) - {boolean=false|string|object}, If `true` will force transition even if no state or params
901      *    have changed.  It will reload the resolves and views of the current state and parent states.
902      *    If `reload` is a string (or state object), the state object is fetched (by name, or object reference); and \
903      *    the transition reloads the resolves and views for that matched state, and all its children states.
904      *
905      * @returns {promise} A promise representing the state of the new transition.
906      *
907      * Possible success values:
908      *
909      * - $state.current
910      *
911      * <br/>Possible rejection values:
912      *
913      * - 'transition superseded' - when a newer transition has been started after this one
914      * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
915      * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
916      *   when a `$stateNotFound` `event.retry` promise errors.
917      * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
918      * - *resolve error* - when an error has occurred with a `resolve`
919      *
920      */
921     $state.go = function go(to, params, options) {
922       return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
923     };
924
925     /**
926      * @ngdoc function
927      * @name ui.router.state.$state#transitionTo
928      * @methodOf ui.router.state.$state
929      *
930      * @description
931      * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
932      * uses `transitionTo` internally. `$state.go` is recommended in most situations.
933      *
934      * @example
935      * <pre>
936      * var app = angular.module('app', ['ui.router']);
937      *
938      * app.controller('ctrl', function ($scope, $state) {
939      *   $scope.changeState = function () {
940      *     $state.transitionTo('contact.detail');
941      *   };
942      * });
943      * </pre>
944      *
945      * @param {string} to State name.
946      * @param {object=} toParams A map of the parameters that will be sent to the state,
947      * will populate $stateParams.
948      * @param {object=} options Options object. The options are:
949      *
950      * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
951      *    will not. If string, must be `"replace"`, which will update url and also replace last history record.
952      * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
953      * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), 
954      *    defines which state to be relative from.
955      * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
956      * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params 
957      *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
958      *    use this when you want to force a reload when *everything* is the same, including search params.
959      *    if String, then will reload the state with the name given in reload, and any children.
960      *    if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
961      *
962      * @returns {promise} A promise representing the state of the new transition. See
963      * {@link ui.router.state.$state#methods_go $state.go}.
964      */
965     $state.transitionTo = function transitionTo(to, toParams, options) {
966       toParams = toParams || {};
967       options = extend({
968         location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
969       }, options || {});
970
971       var from = $state.$current, fromParams = $state.params, fromPath = from.path;
972       var evt, toState = findState(to, options.relative);
973
974       // Store the hash param for later (since it will be stripped out by various methods)
975       var hash = toParams['#'];
976
977       if (!isDefined(toState)) {
978         var redirect = { to: to, toParams: toParams, options: options };
979         var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
980
981         if (redirectResult) {
982           return redirectResult;
983         }
984
985         // Always retry once if the $stateNotFound was not prevented
986         // (handles either redirect changed or state lazy-definition)
987         to = redirect.to;
988         toParams = redirect.toParams;
989         options = redirect.options;
990         toState = findState(to, options.relative);
991
992         if (!isDefined(toState)) {
993           if (!options.relative) throw new Error("No such state '" + to + "'");
994           throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
995         }
996       }
997       if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
998       if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
999       if (!toState.params.$$validates(toParams)) return TransitionFailed;
1000
1001       toParams = toState.params.$$values(toParams);
1002       to = toState;
1003
1004       var toPath = to.path;
1005
1006       // Starting from the root of the path, keep all levels that haven't changed
1007       var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
1008
1009       if (!options.reload) {
1010         while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
1011           locals = toLocals[keep] = state.locals;
1012           keep++;
1013           state = toPath[keep];
1014         }
1015       } else if (isString(options.reload) || isObject(options.reload)) {
1016         if (isObject(options.reload) && !options.reload.name) {
1017           throw new Error('Invalid reload state object');
1018         }
1019         
1020         var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
1021         if (options.reload && !reloadState) {
1022           throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
1023         }
1024
1025         while (state && state === fromPath[keep] && state !== reloadState) {
1026           locals = toLocals[keep] = state.locals;
1027           keep++;
1028           state = toPath[keep];
1029         }
1030       }
1031
1032       // If we're going to the same state and all locals are kept, we've got nothing to do.
1033       // But clear 'transition', as we still want to cancel any other pending transitions.
1034       // TODO: We may not want to bump 'transition' if we're called from a location change
1035       // that we've initiated ourselves, because we might accidentally abort a legitimate
1036       // transition initiated from code?
1037       if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
1038         if (hash) toParams['#'] = hash;
1039         $state.params = toParams;
1040         copy($state.params, $stateParams);
1041         copy(filterByKeys(to.params.$$keys(), $stateParams), to.locals.globals.$stateParams);
1042         if (options.location && to.navigable && to.navigable.url) {
1043           $urlRouter.push(to.navigable.url, toParams, {
1044             $$avoidResync: true, replace: options.location === 'replace'
1045           });
1046           $urlRouter.update(true);
1047         }
1048         $state.transition = null;
1049         return $q.when($state.current);
1050       }
1051
1052       // Filter parameters before we pass them to event handlers etc.
1053       toParams = filterByKeys(to.params.$$keys(), toParams || {});
1054       
1055       // Re-add the saved hash before we start returning things or broadcasting $stateChangeStart
1056       if (hash) toParams['#'] = hash;
1057       
1058       // Broadcast start event and cancel the transition if requested
1059       if (options.notify) {
1060         /**
1061          * @ngdoc event
1062          * @name ui.router.state.$state#$stateChangeStart
1063          * @eventOf ui.router.state.$state
1064          * @eventType broadcast on root scope
1065          * @description
1066          * Fired when the state transition **begins**. You can use `event.preventDefault()`
1067          * to prevent the transition from happening and then the transition promise will be
1068          * rejected with a `'transition prevented'` value.
1069          *
1070          * @param {Object} event Event object.
1071          * @param {State} toState The state being transitioned to.
1072          * @param {Object} toParams The params supplied to the `toState`.
1073          * @param {State} fromState The current state, pre-transition.
1074          * @param {Object} fromParams The params supplied to the `fromState`.
1075          *
1076          * @example
1077          *
1078          * <pre>
1079          * $rootScope.$on('$stateChangeStart',
1080          * function(event, toState, toParams, fromState, fromParams){
1081          *     event.preventDefault();
1082          *     // transitionTo() promise will be rejected with
1083          *     // a 'transition prevented' error
1084          * })
1085          * </pre>
1086          */
1087         if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams, options).defaultPrevented) {
1088           $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
1089           //Don't update and resync url if there's been a new transition started. see issue #2238, #600
1090           if ($state.transition == null) $urlRouter.update();
1091           return TransitionPrevented;
1092         }
1093       }
1094
1095       // Resolve locals for the remaining states, but don't update any global state just
1096       // yet -- if anything fails to resolve the current state needs to remain untouched.
1097       // We also set up an inheritance chain for the locals here. This allows the view directive
1098       // to quickly look up the correct definition for each view in the current state. Even
1099       // though we create the locals object itself outside resolveState(), it is initially
1100       // empty and gets filled asynchronously. We need to keep track of the promise for the
1101       // (fully resolved) current locals, and pass this down the chain.
1102       var resolved = $q.when(locals);
1103
1104       for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
1105         locals = toLocals[l] = inherit(locals);
1106         resolved = resolveState(state, toParams, state === to, resolved, locals, options);
1107       }
1108
1109       // Once everything is resolved, we are ready to perform the actual transition
1110       // and return a promise for the new state. We also keep track of what the
1111       // current promise is, so that we can detect overlapping transitions and
1112       // keep only the outcome of the last transition.
1113       var transition = $state.transition = resolved.then(function () {
1114         var l, entering, exiting;
1115
1116         if ($state.transition !== transition) return TransitionSuperseded;
1117
1118         // Exit 'from' states not kept
1119         for (l = fromPath.length - 1; l >= keep; l--) {
1120           exiting = fromPath[l];
1121           if (exiting.self.onExit) {
1122             $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
1123           }
1124           exiting.locals = null;
1125         }
1126
1127         // Enter 'to' states not kept
1128         for (l = keep; l < toPath.length; l++) {
1129           entering = toPath[l];
1130           entering.locals = toLocals[l];
1131           if (entering.self.onEnter) {
1132             $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
1133           }
1134         }
1135
1136         // Run it again, to catch any transitions in callbacks
1137         if ($state.transition !== transition) return TransitionSuperseded;
1138
1139         // Update globals in $state
1140         $state.$current = to;
1141         $state.current = to.self;
1142         $state.params = toParams;
1143         copy($state.params, $stateParams);
1144         $state.transition = null;
1145
1146         if (options.location && to.navigable) {
1147           $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
1148             $$avoidResync: true, replace: options.location === 'replace'
1149           });
1150         }
1151
1152         if (options.notify) {
1153         /**
1154          * @ngdoc event
1155          * @name ui.router.state.$state#$stateChangeSuccess
1156          * @eventOf ui.router.state.$state
1157          * @eventType broadcast on root scope
1158          * @description
1159          * Fired once the state transition is **complete**.
1160          *
1161          * @param {Object} event Event object.
1162          * @param {State} toState The state being transitioned to.
1163          * @param {Object} toParams The params supplied to the `toState`.
1164          * @param {State} fromState The current state, pre-transition.
1165          * @param {Object} fromParams The params supplied to the `fromState`.
1166          */
1167           $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
1168         }
1169         $urlRouter.update(true);
1170
1171         return $state.current;
1172       }, function (error) {
1173         if ($state.transition !== transition) return TransitionSuperseded;
1174
1175         $state.transition = null;
1176         /**
1177          * @ngdoc event
1178          * @name ui.router.state.$state#$stateChangeError
1179          * @eventOf ui.router.state.$state
1180          * @eventType broadcast on root scope
1181          * @description
1182          * Fired when an **error occurs** during transition. It's important to note that if you
1183          * have any errors in your resolve functions (javascript errors, non-existent services, etc)
1184          * they will not throw traditionally. You must listen for this $stateChangeError event to
1185          * catch **ALL** errors.
1186          *
1187          * @param {Object} event Event object.
1188          * @param {State} toState The state being transitioned to.
1189          * @param {Object} toParams The params supplied to the `toState`.
1190          * @param {State} fromState The current state, pre-transition.
1191          * @param {Object} fromParams The params supplied to the `fromState`.
1192          * @param {Error} error The resolve error object.
1193          */
1194         evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
1195
1196         if (!evt.defaultPrevented) {
1197             $urlRouter.update();
1198         }
1199
1200         return $q.reject(error);
1201       });
1202
1203       return transition;
1204     };
1205
1206     /**
1207      * @ngdoc function
1208      * @name ui.router.state.$state#is
1209      * @methodOf ui.router.state.$state
1210      *
1211      * @description
1212      * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
1213      * but only checks for the full state name. If params is supplied then it will be
1214      * tested for strict equality against the current active params object, so all params
1215      * must match with none missing and no extras.
1216      *
1217      * @example
1218      * <pre>
1219      * $state.$current.name = 'contacts.details.item';
1220      *
1221      * // absolute name
1222      * $state.is('contact.details.item'); // returns true
1223      * $state.is(contactDetailItemStateObject); // returns true
1224      *
1225      * // relative name (. and ^), typically from a template
1226      * // E.g. from the 'contacts.details' template
1227      * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
1228      * </pre>
1229      *
1230      * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
1231      * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
1232      * to test against the current active state.
1233      * @param {object=} options An options object.  The options are:
1234      *
1235      * - **`relative`** - {string|object} -  If `stateOrName` is a relative state name and `options.relative` is set, .is will
1236      * test relative to `options.relative` state (or name).
1237      *
1238      * @returns {boolean} Returns true if it is the state.
1239      */
1240     $state.is = function is(stateOrName, params, options) {
1241       options = extend({ relative: $state.$current }, options || {});
1242       var state = findState(stateOrName, options.relative);
1243
1244       if (!isDefined(state)) { return undefined; }
1245       if ($state.$current !== state) { return false; }
1246       return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
1247     };
1248
1249     /**
1250      * @ngdoc function
1251      * @name ui.router.state.$state#includes
1252      * @methodOf ui.router.state.$state
1253      *
1254      * @description
1255      * A method to determine if the current active state is equal to or is the child of the
1256      * state stateName. If any params are passed then they will be tested for a match as well.
1257      * Not all the parameters need to be passed, just the ones you'd like to test for equality.
1258      *
1259      * @example
1260      * Partial and relative names
1261      * <pre>
1262      * $state.$current.name = 'contacts.details.item';
1263      *
1264      * // Using partial names
1265      * $state.includes("contacts"); // returns true
1266      * $state.includes("contacts.details"); // returns true
1267      * $state.includes("contacts.details.item"); // returns true
1268      * $state.includes("contacts.list"); // returns false
1269      * $state.includes("about"); // returns false
1270      *
1271      * // Using relative names (. and ^), typically from a template
1272      * // E.g. from the 'contacts.details' template
1273      * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
1274      * </pre>
1275      *
1276      * Basic globbing patterns
1277      * <pre>
1278      * $state.$current.name = 'contacts.details.item.url';
1279      *
1280      * $state.includes("*.details.*.*"); // returns true
1281      * $state.includes("*.details.**"); // returns true
1282      * $state.includes("**.item.**"); // returns true
1283      * $state.includes("*.details.item.url"); // returns true
1284      * $state.includes("*.details.*.url"); // returns true
1285      * $state.includes("*.details.*"); // returns false
1286      * $state.includes("item.**"); // returns false
1287      * </pre>
1288      *
1289      * @param {string} stateOrName A partial name, relative name, or glob pattern
1290      * to be searched for within the current state name.
1291      * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
1292      * that you'd like to test against the current active state.
1293      * @param {object=} options An options object.  The options are:
1294      *
1295      * - **`relative`** - {string|object=} -  If `stateOrName` is a relative state reference and `options.relative` is set,
1296      * .includes will test relative to `options.relative` state (or name).
1297      *
1298      * @returns {boolean} Returns true if it does include the state
1299      */
1300     $state.includes = function includes(stateOrName, params, options) {
1301       options = extend({ relative: $state.$current }, options || {});
1302       if (isString(stateOrName) && isGlob(stateOrName)) {
1303         if (!doesStateMatchGlob(stateOrName)) {
1304           return false;
1305         }
1306         stateOrName = $state.$current.name;
1307       }
1308
1309       var state = findState(stateOrName, options.relative);
1310       if (!isDefined(state)) { return undefined; }
1311       if (!isDefined($state.$current.includes[state.name])) { return false; }
1312       return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
1313     };
1314
1315
1316     /**
1317      * @ngdoc function
1318      * @name ui.router.state.$state#href
1319      * @methodOf ui.router.state.$state
1320      *
1321      * @description
1322      * A url generation method that returns the compiled url for the given state populated with the given params.
1323      *
1324      * @example
1325      * <pre>
1326      * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
1327      * </pre>
1328      *
1329      * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
1330      * @param {object=} params An object of parameter values to fill the state's required parameters.
1331      * @param {object=} options Options object. The options are:
1332      *
1333      * - **`lossy`** - {boolean=true} -  If true, and if there is no url associated with the state provided in the
1334      *    first parameter, then the constructed href url will be built from the first navigable ancestor (aka
1335      *    ancestor with a valid url).
1336      * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
1337      * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), 
1338      *    defines which state to be relative from.
1339      * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
1340      * 
1341      * @returns {string} compiled state url
1342      */
1343     $state.href = function href(stateOrName, params, options) {
1344       options = extend({
1345         lossy:    true,
1346         inherit:  true,
1347         absolute: false,
1348         relative: $state.$current
1349       }, options || {});
1350
1351       var state = findState(stateOrName, options.relative);
1352
1353       if (!isDefined(state)) return null;
1354       if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
1355       
1356       var nav = (state && options.lossy) ? state.navigable : state;
1357
1358       if (!nav || nav.url === undefined || nav.url === null) {
1359         return null;
1360       }
1361       return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
1362         absolute: options.absolute
1363       });
1364     };
1365
1366     /**
1367      * @ngdoc function
1368      * @name ui.router.state.$state#get
1369      * @methodOf ui.router.state.$state
1370      *
1371      * @description
1372      * Returns the state configuration object for any specific state or all states.
1373      *
1374      * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
1375      * the requested state. If not provided, returns an array of ALL state configs.
1376      * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
1377      * @returns {Object|Array} State configuration object or array of all objects.
1378      */
1379     $state.get = function (stateOrName, context) {
1380       if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
1381       var state = findState(stateOrName, context || $state.$current);
1382       return (state && state.self) ? state.self : null;
1383     };
1384
1385     function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
1386       // Make a restricted $stateParams with only the parameters that apply to this state if
1387       // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
1388       // we also need $stateParams to be available for any $injector calls we make during the
1389       // dependency resolution process.
1390       var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
1391       var locals = { $stateParams: $stateParams };
1392
1393       // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
1394       // We're also including $stateParams in this; that way the parameters are restricted
1395       // to the set that should be visible to the state, and are independent of when we update
1396       // the global $state and $stateParams values.
1397       dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
1398       var promises = [dst.resolve.then(function (globals) {
1399         dst.globals = globals;
1400       })];
1401       if (inherited) promises.push(inherited);
1402
1403       function resolveViews() {
1404         var viewsPromises = [];
1405
1406         // Resolve template and dependencies for all views.
1407         forEach(state.views, function (view, name) {
1408           var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
1409           injectables.$template = [ function () {
1410             return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';
1411           }];
1412
1413           viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
1414             // References to the controller (only instantiated at link time)
1415             if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
1416               var injectLocals = angular.extend({}, injectables, dst.globals);
1417               result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
1418             } else {
1419               result.$$controller = view.controller;
1420             }
1421             // Provide access to the state itself for internal use
1422             result.$$state = state;
1423             result.$$controllerAs = view.controllerAs;
1424             dst[name] = result;
1425           }));
1426         });
1427
1428         return $q.all(viewsPromises).then(function(){
1429           return dst.globals;
1430         });
1431       }
1432
1433       // Wait for all the promises and then return the activation object
1434       return $q.all(promises).then(resolveViews).then(function (values) {
1435         return dst;
1436       });
1437     }
1438
1439     return $state;
1440   }
1441
1442   function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
1443     // Return true if there are no differences in non-search (path/object) params, false if there are differences
1444     function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
1445       // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
1446       function notSearchParam(key) {
1447         return fromAndToState.params[key].location != "search";
1448       }
1449       var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
1450       var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
1451       var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
1452       return nonQueryParamSet.$$equals(fromParams, toParams);
1453     }
1454
1455     // If reload was not explicitly requested
1456     // and we're transitioning to the same state we're already in
1457     // and    the locals didn't change
1458     //     or they changed in a way that doesn't merit reloading
1459     //        (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
1460     // Then return true.
1461     if (!options.reload && to === from &&
1462       (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
1463       return true;
1464     }
1465   }
1466 }
1467
1468 angular.module('ui.router.state')
1469   .factory('$stateParams', function () { return {}; })
1470   .provider('$state', $StateProvider);