3 * @name ui.router.state.$stateProvider
5 * @requires ui.router.router.$urlRouterProvider
6 * @requires ui.router.util.$urlMatcherFactoryProvider
9 * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
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.
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
20 * The `$stateProvider` provides interfaces to declare these states for your app.
22 $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
23 function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
25 var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
27 // Builds state properties from definition passed to registerState()
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;
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);
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 || {} };
54 if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
55 return (state.parent.navigable || root).url.concat(url, config);
58 if (!url || $urlMatcherFactory.isMatcher(url)) return url;
59 throw new Error("Invalid url '" + url + "' in state '" + state + "'");
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);
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");
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();
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) {
90 forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
91 if (name.indexOf('@') < 0) name += '@' + state.parent.name;
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
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;
112 function isRelative(stateName) {
113 return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
116 function findState(stateOrName, base) {
117 if (!stateOrName) return undefined;
119 var isStr = isString(stateOrName),
120 name = isStr ? stateOrName : stateOrName.name,
121 path = isRelative(name);
124 if (!base) throw new Error("No reference point given for path '" + name + "'");
125 base = findState(base);
127 var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
129 for (; i < pathLength; i++) {
130 if (rel[i] === "" && i === 0) {
134 if (rel[i] === "^") {
135 if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
136 current = current.parent;
141 rel = rel.slice(i).join(".");
142 name = current.name + (current.name && rel ? "." : "") + rel;
144 var state = states[name];
146 if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
152 function queueState(parentName, state) {
153 if (!queue[parentName]) {
154 queue[parentName] = [];
156 queue[parentName].push(state);
159 function flushQueuedChildren(parentName) {
160 var queued = queue[parentName] || [];
161 while(queued.length) {
162 registerState(queued.shift());
166 function registerState(state) {
167 // Wrap a new object around the state so we can store our private details easily.
168 state = inherit(state, {
170 resolve: state.resolve || {},
171 toString: function() { return this.name; }
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");
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
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);
189 for (var key in stateBuilder) {
190 if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
192 states[name] = state;
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 });
203 // Register any queued children
204 flushQueuedChildren(name);
209 // Checks text to see if it looks like a glob.
210 function isGlob (text) {
211 return text.indexOf('*') > -1;
214 // Returns true if glob matches current $state name.
215 function doesStateMatchGlob (glob) {
216 var globSegments = glob.split('.'),
217 segments = $state.$current.name.split('.');
220 for (var i = 0, l = globSegments.length; i < l; i++) {
221 if (globSegments[i] === '*') {
226 //match greedy starts
227 if (globSegments[0] === '**') {
228 segments = segments.slice(indexOf(segments, globSegments[1]));
229 segments.unshift('**');
232 if (globSegments[globSegments.length - 1] === '**') {
233 segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
237 if (globSegments.length != segments.length) {
241 return segments.join('') === globSegments.join('');
245 // Implicit root state that is always active
246 root = registerState({
252 root.navigable = null;
257 * @name ui.router.state.$stateProvider#decorator
258 * @methodOf ui.router.state.$stateProvider
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.
266 * When passing only a name, it returns the current (original or decorated) builder
267 * function that matches `name`.
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.
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.
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.
283 * Existing builder functions and current return values:
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}
290 * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
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.
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) {
313 * views = parent(state);
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;
323 * $stateProvider.state('home', {
325 * 'contact.list': { controller: 'ListController' },
326 * 'contact.item': { controller: 'ItemController' }
333 * // Auto-populates list and item views with /partials/home/contact/list.html,
334 * // and /partials/home/contact/item.html, respectively.
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:
341 * - `{object}` - state - The state config object.
342 * - `{object}` - super - The original builder function.
344 * @return {object} $stateProvider - $stateProvider instance
346 this.decorator = decorator;
347 function decorator(name, func) {
348 /*jshint validthis: true */
349 if (isString(name) && !isDefined(func)) {
350 return stateBuilder[name];
352 if (!isFunction(func) || !isString(name)) {
355 if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
356 stateBuilder.$delegates[name] = stateBuilder[name];
358 stateBuilder[name] = func;
364 * @name ui.router.state.$stateProvider#state
365 * @methodOf ui.router.state.$stateProvider
368 * Registers a state configuration under a given state name. The stateConfig object
369 * has the following acceptable properties.
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.
380 * If `template` is a function, it will be called with the following parameters:
382 * - {array.<object>} - state parameters extracted from the current $location.path() by
383 * applying the current state
386 * "<h1>inline template definition</h1>" +
387 * "<div ui-view></div>"</pre>
388 * <pre>template: function(params) {
389 * return "<h1>generated template</h1>"; }</pre>
392 * @param {string|function=} stateConfig.templateUrl
393 * <a id='templateUrl'></a>
395 * path or function that returns a path to an html
396 * template that should be used by uiView.
398 * If `templateUrl` is a function, it will be called with the following parameters:
400 * - {array.<object>} - state parameters extracted from the current $location.path() by
401 * applying the current state
403 * <pre>templateUrl: "home.html"</pre>
404 * <pre>templateUrl: function(params) {
405 * return myTemplates[params.pageId]; }</pre>
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);
415 * @param {string|function=} stateConfig.controller
416 * <a id='controller'></a>
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>
423 * "MyRegisteredController as fooCtrl"}</pre>
424 * <pre>controller: function($scope, MyService) {
425 * $scope.data = MyService.getData(); }</pre>
427 * @param {function=} stateConfig.controllerProvider
428 * <a id='controllerProvider'></a>
430 * Injectable provider function that returns the actual controller or string.
431 * <pre>controllerProvider:
432 * function(MyResolveData) {
433 * if (MyResolveData.foo)
435 * else if (MyResolveData.bar)
437 * else return function($scope) {
438 * $scope.baz = "Qux";
442 * @param {string=} stateConfig.controllerAs
443 * <a id='controllerAs'></a>
445 * A controller alias name. If present the controller will be
446 * published to scope under the controllerAs name.
447 * <pre>controllerAs: "myCtrl"</pre>
449 * @param {string|object=} stateConfig.parent
450 * <a id='parent'></a>
451 * Optionally specifies the parent state of this state.
453 * <pre>parent: 'parentState'</pre>
454 * <pre>parent: parentState // JS variable</pre>
456 * @param {object=} stateConfig.resolve
457 * <a id='resolve'></a>
459 * An optional map<string, function> 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.
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.
475 * function($http, $stateParams) {
476 * return $http.get("/api/foos/"+stateParams.fooID);
480 * @param {string=} stateConfig.url
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.
487 * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
488 * more details on acceptable patterns )
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}"
501 * @param {object=} stateConfig.views
503 * an optional map<string, object> which defined multiple views, or targets views
504 * manually/explicitly.
508 * Targets three named `ui-view`s in the parent state's template
511 * controller: "headerCtrl",
512 * templateUrl: "header.html"
514 * controller: "bodyCtrl",
515 * templateUrl: "body.html"
517 * controller: "footCtrl",
518 * templateUrl: "footer.html"
522 * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
525 * controller: "msgHeaderCtrl",
526 * templateUrl: "msgHeader.html"
528 * controller: "messagesCtrl",
529 * templateUrl: "messages.html"
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>
539 * @param {function=} stateConfig.onEnter
540 * <a id='onEnter'></a>
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.
547 * <pre>onEnter: function(MyService, $stateParams) {
548 * MyService.foo($stateParams.myParam);
551 * @param {function=} stateConfig.onExit
552 * <a id='onExit'></a>
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.
559 * <pre>onExit: function(MyService, $stateParams) {
560 * MyService.cleanup($stateParams.myParam);
563 * @param {boolean=} [stateConfig.reloadOnSearch=true]
564 * <a id='reloadOnSearch'></a>
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>
571 * @param {object=} stateConfig.data
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.
579 * requiredRole: 'foo'
582 * @param {object=} stateConfig.params
583 * <a id='params'></a>
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.
589 * Each parameter configuration object may contain the following properties:
591 * - ** value ** - {object|function=}: specifies the default value for this
592 * parameter. This implicitly sets this parameter as optional.
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.
599 * *Note*: `undefined` is treated as "no default value" while `null`
600 * is treated as "the default value is `null`".
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.:
607 * <pre>// define a parameter's default value
609 * param1: { value: "defaultValue" }
611 * // shorthand default values
613 * param1: "defaultValue",
614 * param2: "param2Default"
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.
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' }`).
629 * param1: { array: true }
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()`})
637 * There are three squash settings:
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.
647 * value: "defaultId",
650 * // squash "defaultValue" to "~"
653 * value: "defaultValue",
661 * // Some state name examples
663 * // stateName can be a single top-level name (must be unique).
664 * $stateProvider.state("home", {});
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", {});
670 * // Nest states as deeply as needed.
671 * $stateProvider.state("home.newest.abc.xyz.inception", {});
673 * // state() returns $stateProvider, so you can chain state declarations.
676 * .state("about", {})
677 * .state("contacts", {});
682 function state(name, definition) {
683 /*jshint validthis: true */
684 if (isObject(name)) definition = name;
685 else definition.name = name;
686 registerState(definition);
692 * @name ui.router.state.$state
694 * @requires $rootScope
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
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
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.
715 $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
716 function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
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'));
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) {
728 * @name ui.router.state.$state#$stateNotFound
729 * @eventOf ui.router.state.$state
730 * @eventType broadcast on root scope
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.
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.
746 * // somewhere, assume lazy.state has not been defined
747 * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
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
758 var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
760 if (evt.defaultPrevented) {
762 return TransitionAborted;
769 // Allow the handler to return a promise to defer state lookup retry
770 if (options.$retry) {
772 return TransitionFailed;
774 var retryTransition = $state.transition = $q.when(evt.retry);
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);
781 return TransitionAborted;
785 return retryTransition;
788 root.locals = { resolve: null, globals: { $stateParams: {} } };
799 * @name ui.router.state.$state#reload
800 * @methodOf ui.router.state.$state
803 * A method that force reloads the current state. All resolves are re-resolved,
804 * controllers reinstantiated, and events re-fired.
808 * var app angular.module('app', ['ui.router']);
810 * app.controller('ctrl', function ($scope, $state) {
811 * $scope.reload = function(){
817 * `reload()` is just an alias for:
819 * $state.transitionTo($state.current, $stateParams, {
820 * reload: true, inherit: false, notify: true
824 * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
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']);
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');
839 * `reload()` is just an alias for:
841 * $state.transitionTo($state.current, $stateParams, {
842 * reload: true, inherit: false, notify: true
846 * @returns {promise} A promise representing the state of the new transition. See
847 * {@link ui.router.state.$state#methods_go $state.go}.
849 $state.reload = function reload(state) {
850 return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
855 * @name ui.router.state.$state#go
856 * @methodOf ui.router.state.$state
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).
868 * var app = angular.module('app', ['ui.router']);
870 * app.controller('ctrl', function ($scope, $state) {
871 * $scope.changeState = function () {
872 * $state.go('contact.detail');
876 * <img src='../ngdoc_assets/StateGoExamples.png'/>
878 * @param {string} to Absolute state name or relative state path. Some examples:
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
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:
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.
905 * @returns {promise} A promise representing the state of the new transition.
907 * Possible success values:
911 * <br/>Possible rejection values:
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`
921 $state.go = function go(to, params, options) {
922 return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
927 * @name ui.router.state.$state#transitionTo
928 * @methodOf ui.router.state.$state
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.
936 * var app = angular.module('app', ['ui.router']);
938 * app.controller('ctrl', function ($scope, $state) {
939 * $scope.changeState = function () {
940 * $state.transitionTo('contact.detail');
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:
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.
962 * @returns {promise} A promise representing the state of the new transition. See
963 * {@link ui.router.state.$state#methods_go $state.go}.
965 $state.transitionTo = function transitionTo(to, toParams, options) {
966 toParams = toParams || {};
968 location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
971 var from = $state.$current, fromParams = $state.params, fromPath = from.path;
972 var evt, toState = findState(to, options.relative);
974 // Store the hash param for later (since it will be stripped out by various methods)
975 var hash = toParams['#'];
977 if (!isDefined(toState)) {
978 var redirect = { to: to, toParams: toParams, options: options };
979 var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
981 if (redirectResult) {
982 return redirectResult;
985 // Always retry once if the $stateNotFound was not prevented
986 // (handles either redirect changed or state lazy-definition)
988 toParams = redirect.toParams;
989 options = redirect.options;
990 toState = findState(to, options.relative);
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 + "'");
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;
1001 toParams = toState.params.$$values(toParams);
1004 var toPath = to.path;
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 = [];
1009 if (!options.reload) {
1010 while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
1011 locals = toLocals[keep] = state.locals;
1013 state = toPath[keep];
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');
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) + "'");
1025 while (state && state === fromPath[keep] && state !== reloadState) {
1026 locals = toLocals[keep] = state.locals;
1028 state = toPath[keep];
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'
1046 $urlRouter.update(true);
1048 $state.transition = null;
1049 return $q.when($state.current);
1052 // Filter parameters before we pass them to event handlers etc.
1053 toParams = filterByKeys(to.params.$$keys(), toParams || {});
1055 // Re-add the saved hash before we start returning things or broadcasting $stateChangeStart
1056 if (hash) toParams['#'] = hash;
1058 // Broadcast start event and cancel the transition if requested
1059 if (options.notify) {
1062 * @name ui.router.state.$state#$stateChangeStart
1063 * @eventOf ui.router.state.$state
1064 * @eventType broadcast on root scope
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.
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`.
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
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;
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);
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);
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;
1116 if ($state.transition !== transition) return TransitionSuperseded;
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);
1124 exiting.locals = null;
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);
1136 // Run it again, to catch any transitions in callbacks
1137 if ($state.transition !== transition) return TransitionSuperseded;
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;
1146 if (options.location && to.navigable) {
1147 $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
1148 $$avoidResync: true, replace: options.location === 'replace'
1152 if (options.notify) {
1155 * @name ui.router.state.$state#$stateChangeSuccess
1156 * @eventOf ui.router.state.$state
1157 * @eventType broadcast on root scope
1159 * Fired once the state transition is **complete**.
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`.
1167 $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
1169 $urlRouter.update(true);
1171 return $state.current;
1172 }, function (error) {
1173 if ($state.transition !== transition) return TransitionSuperseded;
1175 $state.transition = null;
1178 * @name ui.router.state.$state#$stateChangeError
1179 * @eventOf ui.router.state.$state
1180 * @eventType broadcast on root scope
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.
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.
1194 evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
1196 if (!evt.defaultPrevented) {
1197 $urlRouter.update();
1200 return $q.reject(error);
1208 * @name ui.router.state.$state#is
1209 * @methodOf ui.router.state.$state
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.
1219 * $state.$current.name = 'contacts.details.item';
1222 * $state.is('contact.details.item'); // returns true
1223 * $state.is(contactDetailItemStateObject); // returns true
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>
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:
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).
1238 * @returns {boolean} Returns true if it is the state.
1240 $state.is = function is(stateOrName, params, options) {
1241 options = extend({ relative: $state.$current }, options || {});
1242 var state = findState(stateOrName, options.relative);
1244 if (!isDefined(state)) { return undefined; }
1245 if ($state.$current !== state) { return false; }
1246 return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
1251 * @name ui.router.state.$state#includes
1252 * @methodOf ui.router.state.$state
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.
1260 * Partial and relative names
1262 * $state.$current.name = 'contacts.details.item';
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
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>
1276 * Basic globbing patterns
1278 * $state.$current.name = 'contacts.details.item.url';
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
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:
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).
1298 * @returns {boolean} Returns true if it does include the state
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)) {
1306 stateOrName = $state.$current.name;
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;
1318 * @name ui.router.state.$state#href
1319 * @methodOf ui.router.state.$state
1322 * A url generation method that returns the compiled url for the given state populated with the given params.
1326 * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
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:
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".
1341 * @returns {string} compiled state url
1343 $state.href = function href(stateOrName, params, options) {
1348 relative: $state.$current
1351 var state = findState(stateOrName, options.relative);
1353 if (!isDefined(state)) return null;
1354 if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
1356 var nav = (state && options.lossy) ? state.navigable : state;
1358 if (!nav || nav.url === undefined || nav.url === null) {
1361 return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
1362 absolute: options.absolute
1368 * @name ui.router.state.$state#get
1369 * @methodOf ui.router.state.$state
1372 * Returns the state configuration object for any specific state or all states.
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.
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;
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 };
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;
1401 if (inherited) promises.push(inherited);
1403 function resolveViews() {
1404 var viewsPromises = [];
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 }) || '';
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);
1419 result.$$controller = view.controller;
1421 // Provide access to the state itself for internal use
1422 result.$$state = state;
1423 result.$$controllerAs = view.controllerAs;
1428 return $q.all(viewsPromises).then(function(){
1433 // Wait for all the promises and then return the activation object
1434 return $q.all(promises).then(resolveViews).then(function (values) {
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";
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);
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)))) {
1468 angular.module('ui.router.state')
1469 .factory('$stateParams', function () { return {}; })
1470 .provider('$state', $StateProvider);