Gets the internal State object API
Gets the internal API for a registered state.
Note: the internal State API is subject to change without notice
The context that this view is declared within.
The raw name for the view declaration, i.e., the StateDeclaration.views property name.
A type identifier for the View
This is used when loading prerequisites for the view, before it enters the DOM. Different types of views may load differently (e.g., templateProvider+controllerProvider vs component class)
The normalized context anchor (state name) for the uiViewName
When targeting a ui-view
, the uiViewName
address is anchored to a context name (state name).
The normalized address for the ui-view
which this ViewConfig targets.
A ViewConfig targets a ui-view
in the DOM (relative to the uiViewContextAnchor
) which has
a specific name.
Abstract state indicator
An abstract state can never be directly activated. Use an abstract state to provide inherited properties (url, resolve, data, etc) to children states.
An object which maps resolve
s to component bindings
.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
When using a component declaration (component: 'myComponent'
), each input binding for the component is supplied
data from a resolve of the same name, by default. You may supply data from a different resolve name by mapping it here.
Each key in this object is the name of one of the component's input bindings. Each value is the name of the resolve that should be provided to that binding.
Any component bindings that are omitted from this map get the default behavior of mapping to a resolve of the same name.
$stateProvider.state('foo', {
resolve: {
foo: function(FooService) { return FooService.get(); },
bar: function(BarService) { return BarService.get(); }
},
component: 'Baz',
// The component's `baz` binding gets data from the `bar` resolve
// The component's `foo` binding gets data from the `foo` resolve (default behavior)
bindings: {
baz: 'bar'
}
});
app.component('Baz', {
templateUrl: 'baz.html',
controller: 'BazController',
bindings: {
foo: '<', // foo binding
baz: '<' // baz binding
}
});
The name of the component to use for this view.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
The name of an angular 1.5+ .component()
(or directive with
bindToController and/or scope declaration) which will be used for this view.
Resolve data can be provided to the component via the component's bindings
object (for 1.3+ directives, the
bindToController
is used; for other directives, the scope
declaration is used). For each binding declared
on the component, any resolve with the same name is set on the component's controller instance. The binding
is provided to the component as a one-time-binding. In general, components should likewise declare their
input bindings as one-way ("<").
Note: inside a "views:" block, a bare string "foo"
is shorthand for { component: "foo" }
Note: Mapping from resolve names to component inputs may be specified using bindings.
.state('profile', {
// Use the <my-profile></my-profile> component for the Unnamed view
component: 'MyProfile',
}
.state('messages', {
// use the <nav-bar></nav-bar> component for the view named 'header'
// use the <message-list></message-list> component for the view named 'content'
views: {
header: { component: 'NavBar' },
content: { component: 'MessageList' }
}
}
.state('contacts', {
// Inside a "views:" block, a bare string "NavBar" is shorthand for { component: "NavBar" }
// use the <nav-bar></nav-bar> component for the view named 'header'
// use the <contact-list></contact-list> component for the view named 'content'
views: {
header: 'NavBar',
content: 'ContactList'
}
}
Note: When using component
to define a view, you may not use any of: template
, templateUrl
,
templateProvider
, controller
, controllerProvider
, controllerAs
.
See also: Todd Motto's angular 1.3 and 1.4 backport of .component()
Dynamic component provider function.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
This is an injectable provider function which returns the name of the component to use. The provider will invoked during a Transition in which the view's state is entered. The provider is called after the resolve data is fetched.
componentProvider: function(MyResolveData, $transition$) {
if (MyResolveData.foo) {
return "fooComponent"
} else if ($transition$.to().name === 'bar') {
return "barComponent";
}
}
The view's controller function or name
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
The controller function, or the name of a registered controller. The controller function will be used to control the contents of the directives.uiView directive.
If specified as a string, controllerAs can be declared here, i.e., "FooController as foo" instead of in a separate controllerAs property.
See: Ng1Controller for information about component-level router hooks.
A controller alias name.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
If present, the controller will be published to scope under the controllerAs
name.
See: https://docs.angularjs.org/api/ng/directive/ngController
Dynamic controller provider function.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
This is an injectable provider function which returns the actual controller function, or the name of a registered controller. The provider will invoked during a Transition in which the view's state is entered. The provider is called after the resolve data is fetched.
controllerProvider: function(MyResolveData, $transition$) {
if (MyResolveData.foo) {
return "FooCtrl"
} else if ($transition$.to().name === 'bar') {
return "BarCtrl";
} else {
return function($scope) {
$scope.baz = "Qux";
}
}
}
An inherited property to store state data
This is a spot for you to store inherited state metadata.
Child states' data
object will prototypally inherit from their parent state.
This is a good spot to put metadata such as requiresAuth
.
Note: because prototypal inheritance is used, changes to parent data
objects reflect in the child data
objects.
Care should be taken if you are using hasOwnProperty
on the data
object.
Properties from parent objects will return false for hasOwnProperty
.
A function used to lazy load code
The lazyLoad
function is invoked before the state is activated.
The transition waits while the code is loading.
The function should load the code that is required to activate the state. For example, it may load a component class, or some service code. The function must retur a promise which resolves when loading is complete.
For example, this code lazy loads a service before the abc
state is activated:
.state('abc', {
lazyLoad: (transition, state) => System.import('./abcService')
}
The abcService
file is imported and loaded
(it is assumed that the abcService
file knows how to register itself as a service).
lazyLoad
function is invoked if a transition is going to enter the state.onBefore
transition hook).lazyLoad
function is loading code, it will not be invoked again.
For example, if the user double clicks a ui-sref, lazyLoad
is only invoked once even though there were two transition attempts.
Instead, the existing lazy load promise is re-used.lazyLoad
property is deleted from the state declaration.states
, those states are registered.The original transition is retried (this time without the lazyLoad
property present).
If the lazyLoad
function fails, then the transition also fails.
The failed transition (and the lazyLoad
function) could potentially be retried by the user.
State definitions can also be lazy loaded. This might be desirable when building large, multi-module applications.
To lazy load state definitions, a Future State should be registered as a placeholder. When the state definitions are lazy loaded, the Future State is deregistered.
A future state can act as a placeholder for a single state, or for an entire module of states and substates. A future state should have:
name
which ends in .**
.
A future state's name
property acts as a wildcard Glob.
It matches any state name that starts with the name
(including child states that are not yet loaded).url
prefix.
A future state's url
property acts as a wildcard.
UI-Router matches all paths that begin with the url
.
It effectively appends .*
to the internal regular expression.
When the prefix matches, the future state will begin loading.lazyLoad
function.
This function should should return a Promise to lazy load the code for one or more StateDeclaration objects.
It should return a LazyLoadResult.
Generally, one of the lazy loaded states should have the same name as the future state.
The new state will then replace the future state placeholder in the registry.For in depth information on lazy loading and Future States, see the Lazy Loading Guide.
// This child state is a lazy loaded future state
// The `lazyLoad` function loads the final state definition
{
name: 'parent.**',
url: '/parent',
lazyLoad: () => System.import('./lazy.states.js')
}
This file is lazy loaded. It exports an array of states.
import {ChildComponent} from "./child.component.js";
import {ParentComponent} from "./parent.component.js";
// This fully defined state replaces the future state
let parentState = {
// the name should match the future state
name: 'parent',
url: '/parent/:parentId',
component: ParentComponent,
resolve: {
parentData: ($transition$, ParentService) =>
ParentService.get($transition$.params().parentId)
}
}
let childState = {
name: 'parent.child',
url: '/child/:childId',
params: {
childId: "default"
},
resolve: {
childData: ($transition$, ChildService) =>
ChildService.get($transition$.params().childId)
}
};
// This array of states will be registered by the lazyLoad hook
let lazyLoadResults = {
states: [ parentState, childState ]
};
export default lazyLoadResults;
The state name (required)
A unique state name, e.g. "home"
, "about"
, "contacts"
.
To create a parent/child state use a dot, e.g. "about.sales"
, "home.newest"
.
Note: [State] objects require unique names. The name is used like an id.
State hook that can be injected with $transition$
or $state$
for the current transition.
$stateProvider.state({
name: 'mystate',
onEnter: (MyService, $transition$, $state$) => {
return MyService.doSomething($state$.name, $transition$.params());
}
});
State hook that can be injected with $transition$
or $state$
for the current transition.
$stateProvider.state({
name: 'mystate',
onExit: (MyService, $transition$, $state$) => {
return MyService.doSomething($state$.name, $transition$.params());
}
});
State hook that can be injected with $transition$
or $state$
for the current transition.
$stateProvider.state({
name: 'mystate',
onRetain: (MyService, $transition$, $state$) => {
return MyService.doSomething($state$.name, $transition$.params());
}
});
Params configuration
An object which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a ParamDeclaration keyed to the name of the parameter.
params: {
param1: {
type: "int",
array: true,
value: []
},
param2: {
value: "index"
}
}
The parent state
Normally, a state's parent is implied from the state's name, e.g., "parentstate.childstate"
.
Alternatively, you can explicitly set the parent state using this property.
This allows shorter state names, e.g., <a ui-sref="childstate">Child</a>
instead of `Child
When using this property, the state's name should not have any dots in it.
var parentstate = {
name: 'parentstate'
}
var childstate = {
name: 'childstate',
parent: 'parentstate'
// or use a JS var which is the parent StateDeclaration, i.e.:
// parent: parentstate
}
Synchronously or asynchronously redirects Transitions to a different state/params
If this property is defined, a Transition directly to this state will be redirected based on the property's value.
If the value is a string
, the Transition is redirected to the state named by the string.
If the property is an object with a state
and/or params
property,
the Transition is redirected to the named state
and/or params
.
If the value is a TargetState the Transition is redirected to the TargetState
If the property is a function:
Note: redirectTo
is processed as an onStart
hook, before LAZY
resolves.
If your redirect function relies on resolve data, get the Transition.injector and get a
promise for the resolve data using UIInjector.getAsync.
// a string
.state('A', {
redirectTo: 'A.B'
})
// a {state, params} object
.state('C', {
redirectTo: { state: 'C.D', params: { foo: 'index' } }
})
// a fn
.state('E', {
redirectTo: () => "A"
})
// a fn conditionally returning a {state, params}
.state('F', {
redirectTo: (trans) => {
if (trans.params().foo < 10)
return { state: 'F', params: { foo: 10 } };
}
})
// a fn returning a promise for a redirect
.state('G', {
redirectTo: (trans) => {
let svc = trans.injector().get('SomeAsyncService')
let promise = svc.getAsyncRedirectTo(trans.params.foo);
return promise;
}
})
// a fn that fetches resolve data
.state('G', {
redirectTo: (trans) => {
// getAsync tells the resolve to load
let resolvePromise = trans.injector().getAsync('SomeResolve')
return resolvePromise.then(resolveData => resolveData === 'login' ? 'login' : null);
}
})
Makes all search/query parameters dynamic
Resolve - a mechanism to asynchronously fetch data, participating in the Transition lifecycle
The resolve:
property defines data (or other dependencies) to be fetched asynchronously when the state
is being entered. After the data is fetched, it can be used in views, transition hooks or other resolves
that belong to this state, or to any views or resolves that belong to nested states.
Each array element should either be:
{ token: 'token', resolveFn: (http) => http.get('/'), deps: [ Http ] }
new Resolvable('token', (http) => http.get('/'), [ Http ])
{ provide: 'token', useFactory: (http) => http.get('/'), deps: [ Http ] }
import {Resolvable} from "ui-router-ng2"; // or "angular-ui-router"
...
resolve: [
// If you inject `myStateDependency` into a component, you'll get "abc"
{ provide: 'myStateDependency', useFactory: () => 'abc' }, // ng2 style provide literal
new Resolvable('myFoos', (http, trans) => http.get(`/foos/${trans.params().fooId}`), [Http, Transition])
]
Note: You cannot specify a policy for each Resolvable, nor can you use non-string
tokens when using the object style resolve:
block.
resolve: {
// If you inject `myStateDependency` into a controller, you'll get "abc"
myStateDependency: function() {
return "abc";
},
myAsyncData: ['$http', '$transition$' function($http, $transition$) {
// Return a promise (async) for the data
return $http.get("/foos/" + $transition$.params().foo);
}]
}
Since a resolve function can return a promise, the router will delay entering the state until the promises are ready. If any of the promises are rejected, the Transition is aborted with an Error.
By default, resolves for a state are fetched just before that state is entered. Note that only states
which are being entered have their resolves fetched. States that are "retained" do not have their resolves
re-fetched. If you are currently in a parent state A
and are transitioning to a child state A.B
, the
previously resolved data for state A
can be injected into A.B
without delay.
Any resolved data for A.B
is retained until A.B
is exited, e.g., by transitioning back to the parent state A
.
Because of this, resolves are a great place to fetch your application's primary data.
During a transition, Resolve data can be injected into:
Since resolve functions are injected, a common pattern is to inject a custom service such as UserService
and delegate to a custom service method, such as UserService.list()
;
An Angular 1 resolve function can inject some special values:
$transition$
: The current Transition object; information and API about the current transition, such as
"to" and "from" State Parameters and transition options.$stateParams
: (deprecated) The parameters for the current state (Note: these parameter values areAn Angular 2 resolve function can inject some special values:
Transition
: The current Transition object; information and API about the current transition, such as
"to" and "from" State Parameters and transition options.// Injecting a resolve into another resolve
resolve: [
// Define a resolve 'allusers' which delegates to the UserService.list()
// which returns a promise (async) for all the users
{ provide: 'allusers', useFactory: (UserService) => UserService.list(), deps: [UserService] },
// Define a resolve 'user' which depends on the allusers resolve.
// This resolve function is not called until 'allusers' is ready.
{ provide: 'user', (allusers, trans) => _.find(allusers, trans.params().userId, deps: ['allusers', Transition] }
}
The scope variable name to use for resolve data.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
When a view is activated, the resolved data for the state which the view belongs to is put on the scope. This property sets the name of the scope variable to use for the resolved data.
Defaults to $resolve
.
Sets the resolve policy defaults for all resolves on this state
This should be an ResolvePolicy object.
It can contain the following optional keys/values:
when
: (optional) defines when the resolve is fetched. Accepted values: "LAZY" or "EAGER"async
: (optional) if the transition waits for the resolve. Accepted values: "WAIT", "NOWAIT", "RXWAIT"See ResolvePolicy for more details.
The HTML template for the view.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
HTML template as a string, or a function which returns an html template as a string. This template will be used to render the corresponding directives.uiView directive.
This property takes precedence over templateUrl.
If template
is a function, it will be called with the Transition parameters as the first argument.
template: "<h1>inline template definition</h1><div ui-view></div>"
template: function(params) {
return "<h1>generated template</h1>";
}
Injected function which returns the HTML template.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
Injected function which returns the HTML template. The template will be used to render the corresponding directives.uiView directive.
templateProvider: function(MyTemplateService, $transition$) {
return MyTemplateService.getTemplate($transition$.params().pageId);
}
The URL for the HTML template for the view.
A property of Ng1StateDeclaration or Ng1ViewDeclaration:
A path or a function that returns a path to an html template. The template will be fetched and used to render the corresponding directives.uiView directive.
If templateUrl
is a function, it will be called with the Transition parameters as the first argument.
templateUrl: "/templates/home.html"
templateUrl: function(params) {
return myTemplates[params.pageId];
}
The url fragment for the state
A URL fragment (with optional parameters) which is used to match the browser location with this state.
This fragment will be appended to the parent state's URL in order to build up the overall URL for this state. See UrlMatcher for details on acceptable patterns.
An optional object which defines multiple named views.
Each key is the name of a view, and each value is a Ng1ViewDeclaration.
Unnamed views are internally renamed to $default
.
A view's name is used to match an active <ui-view>
directive in the DOM. When the state
is entered, the state's views are activated and matched with active <ui-view>
directives:
The view's name is processed into a ui-view target:
Examples:
Targets three named ui-views in the parent state's template
views: {
header: {
controller: "headerCtrl",
templateUrl: "header.html"
},
body: {
controller: "bodyCtrl",
templateUrl: "body.html"
},
footer: "footerComponent"
}
// Targets named ui-view="header" in the template of the ancestor state 'top'
// and the named `ui-view="body" from the parent state's template.
views: {
'header@top': {
controller: "msgHeaderCtrl",
templateUrl: "msgHeader.html"
},
'body': {
controller: "messagesCtrl",
templateUrl: "messages.html"
}
}
There are a few styles of view addressing/targeting.
The most common is a simple ui-view
name
Addresses without an @
are anchored to the parent state.
// target the `<div ui-view='foo'></div>` created in the parent state's view
views: {
foo: {...}
}
You can anchor the ui-view
name to a specific state by including an @
targets the <div ui-view='foo'></div>
which was created in a view owned by the state bar.baz
views: {
'foo@bar.baz': {...}
}
You can address a ui-view
absolutely, using dotted notation, by prefixing the address with a !
.
Dotted addresses traverse the hierarchy of ui-view
s active in the DOM:
absolutely targets the <div ui-view='nested'></div>
... which was created in the unnamed/$default root <ui-view></ui-view>
views: {
'!$default.nested': {...}
}
Absolute addressing is actually relative addressing, anchored to the unnamed root state (""
).
You can also use relative addressing anchored to any state, in order to target a target deeply nested ui-views
:
The ui-view
is targeted relative to the anchored state by traversing the nested ui-view
names.
targets the <div ui-view='bar'></div>
... which was created inside the
<div ui-view='foo'></div>
... which was created inside the parent state's template.
views: {
'foo.bar': {...}
}
targets the <div ui-view='bar'></div>
... which was created in <div ui-view='foo'></div>
... which was created in a template from the state baz.qux
views: {
'foo.bar@baz.qux': {...}
}
a view can relatively target a named ui-view
defined on an ancestor using ^
(meaning "parent")
views: {
'foo@^': {...}, // foo@(parent state) (same as simply 'foo')
'bar@^.^': {...}, // bar@(grandparent state)
'baz@^.^.^': {...}, // baz@(great-grandparent state)
}
For additional in-depth details about how ui-view
addressing works, see the internal api [[ViewService.match]].
views:
incompatiblityIf a state has a views
object, any state-level view properties (Ng1ViewDeclaration) are ignored. Therefore,
if any view for a state is declared in the views
object, then all of the state's views must be defined in
the views
object. The state declaration must not have any of the following fields:
Generated using TypeDoc
The StateDeclaration object is used to define a state or nested state. It should be registered with the StateRegistry.
Example:
// StateDeclaration object var foldersState = { name: 'folders', url: '/folders', resolve: { allfolders: function(FolderService) { return FolderService.list(); } }, template: "<ul><li ng-repeat='folder in allfolders'></li></ul>", controller: function(allfolders, $scope) { $scope.allfolders = allfolders; } }
Since this interface extends Ng1ViewDeclaration, any view declaration properties can be set directly on the state declaration and they will be applied to the view with the name
$default
. For example:var state = { name: 'foo', url: '/foo', template: '<h1>foo</h1>', controller: 'FooController' }
is simply syntactic sugar for:
If a state definition contains a
views:
object, any view properties set directly on the state are ignored. Thus, this is an invalid state defintion: