@uirouter/core
- Version 6.1.1
- Published
- 4.61 MB
- No dependencies
- MIT license
Install
npm i @uirouter/core
yarn add @uirouter/core
pnpm add @uirouter/core
Overview
UI-Router Core: Framework agnostic, State-based routing for JavaScript Single Page Apps
Index
Variables
Functions
- all()
- allTrueR()
- ancestors()
- and()
- any()
- anyTrueR()
- applyPairs()
- arrayTuples()
- assertFn()
- assertMap()
- assertPredicate()
- beforeAfterSubstr()
- buildUrl()
- compose()
- copy()
- createProxyFunctions()
- curry()
- defaults()
- deregAll()
- eq()
- filter()
- find()
- flatten()
- flattenR()
- fnToString()
- functionToString()
- getParams()
- hashLocationPlugin()
- identity()
- inherit()
- invoke()
- is()
- isArray()
- isDate()
- isFunction()
- isInjectable()
- isNull()
- isNumber()
- isObject()
- isPromise()
- isRegExp()
- isString()
- isUndefined()
- joinNeighborsR()
- kebobString()
- keyValsToObjectR()
- locationPluginFactory()
- makeEvent()
- makeStub()
- map()
- mapObj()
- maxLength()
- memoryLocationPlugin()
- mergeR()
- noop()
- not()
- omit()
- or()
- padString()
- pairs()
- parse()
- parseUrl()
- pattern()
- pick()
- pipe()
- pluck()
- prop()
- pushR()
- pushStateLocationPlugin()
- resolvablesBuilder()
- servicesPlugin()
- silenceUncaughtInPromise()
- silentRejection()
- splitEqual()
- splitHash()
- splitOnDelim()
- splitQuery()
- stringify()
- stripLastPathElement()
- tail()
- trimHashVal()
- uniqR()
- unnest()
- unnestR()
- val()
- values()
Classes
Transition
- $id
- abort()
- addResolvable()
- dynamic()
- entering()
- error()
- exiting()
- from()
- getResolveTokens()
- ignored()
- injector()
- is()
- isActive
- onEnter()
- onError()
- onExit()
- onFinish()
- onRetain()
- onStart()
- onSuccess()
- options()
- originalTransition()
- params()
- paramsChanged()
- promise
- redirectedFrom()
- retained()
- router
- success
- targetState()
- to()
- toString()
- treeChanges()
- valid()
- views()
Interfaces
Enums
Type Aliases
Variables
variable $injector
const $injector: $InjectorLike;
A basic angular1-like injector api
This object implements four methods similar to the [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector)
UI-Router evolved from an angular 1 library to a framework agnostic library. However, some of the
@uirouter/core
code uses these ng1 style APIs to support ng1 style dependency injection.This object provides a naive implementation of a globally scoped dependency injection system. It supports the following DI approaches:
### Function parameter names
A function's
.toString()
is called, and the parameter names are parsed. This only works when the parameter names aren't "mangled" by a minifier such as UglifyJS.function injectedFunction(FooService, BarService) {// FooService and BarService are injected}### Function annotation
A function may be annotated with an array of dependency names as the
$inject
property.injectedFunction.$inject = [ 'FooService', 'BarService' ];function injectedFunction(fs, bs) {// FooService and BarService are injected as fs and bs parameters}### Array notation
An array provides the names of the dependencies to inject (as strings). The function is the last element of the array.
[ 'FooService', 'BarService', function (fs, bs) {// FooService and BarService are injected as fs and bs parameters}]{$InjectorLike}
variable $q
const $q: $QLike;
An angular1-like promise api
This object implements four methods similar to the [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q)
UI-Router evolved from an angular 1 library to a framework agnostic library. However, some of the
@uirouter/core
code uses these ng1 style APIs to support ng1 style dependency injection.This API provides native ES6 promise support wrapped as a $q-like API. Internally, UI-Router uses this $q object to perform promise operations. The
angular-ui-router
(ui-router for angular 1) uses the $q API provided by angular.$q-like promise api
variable defaultResolvePolicy
let defaultResolvePolicy: ResolvePolicy;
variable defaultTransOpts
let defaultTransOpts: TransitionOptions;
The default [[Transition]] options.
Include this object when applying custom defaults: let reloadOpts = { reload: true, notify: true } let options = defaults(theirOpts, customDefaults, defaultOptions);
variable equals
const equals: any;
variable extend
const extend: (toObj: Obj, ...fromObjs: Obj[]) => any;
variable forEach
const forEach: any;
variable fromJson
const fromJson: any;
variable hostRegex
const hostRegex: RegExp;
variable inArray
const inArray: { (array: any[], obj: any): boolean; (array: any[]): (obj: any) => boolean;};
Given an array, returns true if the object is found in the array, (using indexOf)
variable isDefined
const isDefined: Predicate<any>;
variable isNullOrUndefined
const isNullOrUndefined: Predicate<any>;
variable NATIVE_INJECTOR_TOKEN
const NATIVE_INJECTOR_TOKEN: string;
variable propEq
const propEq: Function;
Given a property name and a value, returns a function that returns a boolean based on whether the passed object has a property that matches the value let obj = { foo: 1, name: "blarg" }; let getName = propEq("name", "blarg"); getName(obj) === true
variable pushTo
const pushTo: { <T>(arr: T[], val: T): T; <T>(arr: T[]): (val: T) => T };
pushes a values to an array and returns the value
variable removeFrom
const removeFrom: { <T>(array: T[], obj: T): T[]; <T>(array: T[]): (obj: T) => T[] };
Given an array, and an item, if the item is found in the array, it removes it (in-place). The same array is returned
variable resolvePolicies
let resolvePolicies: { when: { LAZY: string; EAGER: string }; async: { WAIT: string; NOWAIT: string };};
variable root
const root: any;
variable services
const services: CoreServices;
variable toJson
const toJson: any;
variable trace
const trace: Trace;
The [[Trace]] singleton
#### Example:
import {trace} from "@uirouter/core";trace.enable(1, 5);
Functions
function all
all: (fn1: Predicate<any>) => (arr: any[]) => boolean;
Check if all the elements of an array match a predicate function
Parameter fn1
a predicate function
fn1
Returns
a function which takes an array and returns true if
fn1
is true for all elements of the array
function allTrueR
allTrueR: (memo: boolean, elem: any) => any;
Reduce function that returns true if all of the values are truthy.
Example 1
let vals = [ 1, true, {}, "hello world"];vals.reduce(allTrueR, true); // truevals.push(0);vals.reduce(allTrueR, true); // false
function ancestors
ancestors: (first: StateObject, second: StateObject) => StateObject[];
Finds the common ancestor path between two states.
Parameter first
The first state.
Parameter second
The second state. {Array} Returns an array of state names in descending order, not including the root.
function and
and: (fn1: Predicate<any>, fn2: Predicate<any>) => Predicate<any>;
Given two functions that return truthy or falsey values, returns a function that returns truthy if both functions return truthy for the given arguments
function any
any: (fn1: Predicate<any>) => (arr: any[]) => boolean;
function anyTrueR
anyTrueR: (memo: boolean, elem: any) => any;
Reduce function that returns true if any of the values are truthy.
*
Example 1
let vals = [ 0, null, undefined ];vals.reduce(anyTrueR, true); // falsevals.push("hello world");vals.reduce(anyTrueR, true); // true
function applyPairs
applyPairs: (memo: TypedMap<any>, keyValTuple: any[]) => TypedMap<any>;
Reduce function which builds an object from an array of [key, value] pairs.
Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.
Each keyValueTuple should be an array with values [ key: string, value: any ]
Example 1
var pairs = [ ["fookey", "fooval"], ["barkey", "barval"] ]var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})// pairsToObj == { fookey: "fooval", barkey: "barval" }// Or, more simply:var pairsToObj = pairs.reduce(applyPairs, {})// pairsToObj == { fookey: "fooval", barkey: "barval" }
function arrayTuples
arrayTuples: (...args: any[]) => any[];
Given two or more parallel arrays, returns an array of tuples where each tuple is composed of [ a[i], b[i], ... z[i] ]
Example 1
let foo = [ 0, 2, 4, 6 ];let bar = [ 1, 3, 5, 7 ];let baz = [ 10, 30, 50, 70 ];arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]
function assertFn
assertFn: (predicateOrMap: Function, errMsg?: string | Function) => any;
function assertMap
assertMap: <T, U>(mapFn: (t: T) => U, errMsg: string | Function) => (t: T) => U;
Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.
Example 1
var data = { foo: 1, bar: 2 };let keys = [ 'foo', 'bar' ]let values = keys.map(assertMap(key => data[key], "Key not found"));// values is [1, 2]let keys = [ 'foo', 'bar', 'baz' ]let values = keys.map(assertMap(key => data[key], "Key not found"));// throws Error("Key not found")
function assertPredicate
assertPredicate: <T>( predicate: Predicate<T>, errMsg: string | Function) => Predicate<T>;
Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.
Example 1
let isNumber = (obj) => typeof(obj) === 'number';let allNumbers = [ 1, 2, 3, 4, 5 ];allNumbers.filter(assertPredicate(isNumber)); //OKlet oneString = [ 1, 2, 3, 4, "5" ];oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers"");
function beforeAfterSubstr
beforeAfterSubstr: (char: string) => (str: string) => string[];
Returns a function that splits a string on a character or substring
function buildUrl
buildUrl: (loc: LocationServices) => string;
function compose
compose: () => () => any;
Given a varargs list of functions, returns a function that composes the argument functions, right-to-left given: f(x), g(x), h(x) let composed = compose(f,g,h) then, composed is: f(g(h(x)))
function copy
copy: (src: Obj, dest?: Obj) => any;
shallow copy from src to dest
function createProxyFunctions
createProxyFunctions: ( source: Function, target: Obj, bind: Function, fnNames?: string[], latebind?: boolean) => Obj;
Builds proxy functions on the
to
object which pass through to thefrom
object.For each key in
fnNames
, creates a proxy function on theto
object. The proxy function calls the real function on thefrom
object.#### Example: This example creates an new class instance whose functions are prebound to the new'd object.
class Foo {constructor(data) {// Binds all functions from Foo.prototype to 'this',// then copies them to 'this'bindFunctions(Foo.prototype, this, this);this.data = data;}log() {console.log(this.data);}}let myFoo = new Foo([1,2,3]);var logit = myFoo.log;logit(); // logs [1, 2, 3] from the myFoo 'this' instance#### Example: This example creates a bound version of a service function, and copies it to another object
var SomeService = {this.data = [3, 4, 5];this.log = function() {console.log(this.data);}}// Constructor fnfunction OtherThing() {// Binds all functions from SomeService to SomeService,// then copies them to 'this'bindFunctions(SomeService, this, SomeService);}let myOtherThing = new OtherThing();myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'Parameter source
A function that returns the source object which contains the original functions to be bound
Parameter target
A function that returns the target object which will receive the bound functions
Parameter bind
A function that returns the object which the functions will be bound to
Parameter fnNames
The function names which will be bound (Defaults to all the functions found on the 'from' object)
Parameter latebind
If true, the binding of the function is delayed until the first time it's invoked
function curry
curry: (fn: Function) => Function;
Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.
Given a function with N parameters, returns a new function that supports partial application. The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters, where M is less than N, it returns a new function that accepts the remaining parameters. It continues to accept more parameters until all N parameters have been supplied.
This contrived example uses a partially applied function as an predicate, which returns true if an object is found in both arrays.
Parameter fn
Returns
{*|function(): (*|any)}
Example 1
// returns true if an object is in both of the two arraysfunction inBoth(array1, array2, object) {return array1.indexOf(object) !== -1 &&array2.indexOf(object) !== 1;}let obj1, obj2, obj3, obj4, obj5, obj6, obj7let foos = [obj1, obj3]let bars = [obj3, obj4, obj5]// A curried "copy" of inBothlet curriedInBoth = curry(inBoth);// Partially apply both the array1 and array2let inFoosAndBars = curriedInBoth(foos, bars);// Supply the final argument; since all arguments are// supplied, the original inBoth function is then called.let obj1InBoth = inFoosAndBars(obj1); // false// Use the inFoosAndBars as a predicate.// Filter, on each iteration, supplies the final argumentlet allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]
function defaults
defaults: (opts: any, ...defaultsList: Obj[]) => any;
Applies a set of defaults to an options object. The options object is filtered to only those properties of the objects in the defaultsList. Earlier objects in the defaultsList take precedence when applying defaults.
function deregAll
deregAll: (functions: Function[]) => void;
Given an array of (deregistration) functions, calls all functions and removes each one from the source array
function eq
eq: (comp: any) => Predicate<any>;
Given a value, returns a Predicate function that returns true if another value is === equal to the original value
function filter
filter: { <T>(collection: T[], callback: (t: T, key?: number) => boolean): T[]; <T>( collection: TypedMap<T>, callback: (t: T, key?: string) => boolean ): TypedMap<T>;};
Given an array of objects, returns a new array containing only the elements which passed the callback predicate
Given an object, returns a new object with only those properties that passed the callback predicate
function find
find: { <T>(collection: TypedMap<T>, callback: Predicate<T>): T; <T>(collection: T[], callback: Predicate<T>): T;};
Given an object, return the first property of that object which passed the callback predicate
Given an array of objects, returns the first object which passed the callback predicate
function flatten
flatten: (arr: any[]) => any;
Return a completely flattened version of an array.
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];flatten(input) // [ "a", "b", "c", "d", "double, "nested" ]
function flattenR
flattenR: (memo: any[], elem: any) => any[];
Reduce function which recursively un-nests all arrays
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];input.reduce(unnestR, []) // [ "a", "b", "c", "d", "double, "nested" ]
function fnToString
fnToString: (fn: IInjectable) => any;
function functionToString
functionToString: (fn: Function) => any;
function getParams
getParams: (queryString: string) => any;
function hashLocationPlugin
hashLocationPlugin: (router: UIRouter) => LocationPlugin;
A
UIRouterPlugin
uses the browser hash to get/set the current location
function identity
identity: (x: any) => any;
function inherit
inherit: (parent: Obj, extra?: Obj) => any;
prototypal inheritance helper. Creates a new object which has
parent
object as its prototype, and then copies the properties fromextra
onto it
function invoke
invoke: { (fnName: string): Function; (fnName: string, args: any[]): Function };
function is
is: <T>(ctor: new (...args: any[]) => T) => (obj: any) => obj is T;
Given a class, returns a Predicate function that returns true if the object is of that class
function isArray
isArray: (arg: any) => arg is any[];
function isDate
isDate: (x: any) => x is Date;
function isFunction
isFunction: (x: any) => x is Function;
function isInjectable
isInjectable: (val: any) => boolean;
Predicate which checks if a value is injectable
A value is "injectable" if it is a function, or if it is an ng1 array-notation-style array where all the elements in the array are Strings, except the last one, which is a Function
function isNull
isNull: (o: any) => boolean;
function isNumber
isNumber: (x: any) => x is number;
function isObject
isObject: (x: any) => boolean;
function isPromise
isPromise: (x: any) => x is Promise<any>;
Predicate which checks if a value looks like a Promise
It is probably a Promise if it's an object, and it has a
then
property which is a Function
function isRegExp
isRegExp: (x: any) => x is RegExp;
function isString
isString: (x: any) => x is string;
function isUndefined
isUndefined: (x: any) => boolean;
function joinNeighborsR
joinNeighborsR: (acc: any[], x: any) => any[];
Reduce fn that joins neighboring strings
Given an array of strings, returns a new array where all neighboring strings have been joined.
#### Example:
let arr = ["foo", "bar", 1, "baz", "", "qux" ];arr.reduce(joinNeighborsR, []) // ["foobar", 1, "bazqux" ]
function kebobString
kebobString: (camelCase: string) => string;
function keyValsToObjectR
keyValsToObjectR: (accum: any, [key, val]: [any, any]) => any;
function locationPluginFactory
locationPluginFactory: ( name: string, isHtml5: boolean, serviceClass: new (uiRouter?: UIRouter) => LocationServices, configurationClass: new ( uiRouter?: UIRouter, isHtml5?: boolean ) => LocationConfig) => (uiRouter: UIRouter) => { name: string; service: LocationServices; configuration: LocationConfig; dispose: (router: UIRouter) => void;};
function makeEvent
makeEvent: ( registry: IHookRegistry, transitionService: TransitionService, eventType: TransitionEventType) => (matchObject: any, callback: any, options?: {}) => any;
Return a registration function of the requested type.
function makeStub
makeStub: <T>(service: string, methods: (keyof T)[]) => T;
function map
map: { <T, U>(collection: T[], callback: Mapper<T, U>, target?: typeof collection): U[]; <T, U>( collection: { [key: string]: T }, callback: Mapper<T, U>, target?: { [key: string]: T } ): { [key: string]: U };};
Given an array, returns a new array, where each element is transformed by the callback function
function mapObj
mapObj: <T, U>( collection: { [key: string]: T }, callback: Mapper<T, U>, target?: { [key: string]: T }) => { [key: string]: U };
Given an object, returns a new object, where each property is transformed by the callback function
function maxLength
maxLength: (max: number, str: string) => string;
Returns a string shortened to a maximum length
If the string is already less than the
max
length, return the string. Else return the string, shortened tomax - 3
and append three dots ("...").Parameter max
the maximum length of the string to return
Parameter str
the input string
function memoryLocationPlugin
memoryLocationPlugin: (router: UIRouter) => LocationPlugin;
A
UIRouterPlugin
that gets/sets the current location from an in-memory object
function mergeR
mergeR: (memo: Obj, item: Obj) => any;
Reduce function that merges each element of the list into a single object, using extend
function noop
noop: () => any;
function not
not: (fn: Predicate<any>) => Predicate<any>;
Given a function that returns a truthy or falsey value, returns a function that returns the opposite (falsey or truthy) value given the same inputs
function omit
omit: (obj: Obj, propNames: string[]) => Obj;
Return a copy of the object omitting the blacklisted properties.
Parameter obj
the source object
Parameter propNames
an Array of strings, which are the blacklisted property names
Example 1
var foo = { a: 1, b: 2, c: 3 };var ab = omit(foo, ['a', 'b']); // { c: 3 }
function or
or: (fn1: Predicate<any>, fn2: Predicate<any>) => Predicate<any>;
Given two functions that return truthy or falsey values, returns a function that returns truthy if at least one of the functions returns truthy for the given arguments
function padString
padString: (length: number, str: string) => string;
Returns a string, with spaces added to the end, up to a desired str length
If the string is already longer than the desired length, return the string. Else returns the string, with extra spaces on the end, such that it reaches
length
characters.Parameter length
the desired length of the string to return
Parameter str
the input string
function pairs
pairs: (obj: Obj) => any[][];
Like _.pairs: Given an object, returns an array of key/value pairs
Example 1
pairs({ foo: "FOO", bar: "BAR }) // [ [ "foo", "FOO" ], [ "bar": "BAR" ] ]
function parse
parse: (name: string) => any;
Given a dotted property name, returns a function that returns a nested property from an object, or undefined let obj = { id: 1, nestedObj: { foo: 1, name: "blarg" }, }; let getName = prop("nestedObj.name"); getName(obj) === "blarg" let propNotFound = prop("this.property.doesnt.exist"); propNotFound(obj) === undefined
function parseUrl
parseUrl: (url: string) => { path: any; search: any; hash: any; url: string };
function pattern
pattern: (struct: Function[][]) => Function;
Sorta like Pattern Matching (a functional programming conditional construct)
See http://c2.com/cgi/wiki?PatternMatching
This is a conditional construct which allows a series of predicates and output functions to be checked and then applied. Each predicate receives the input. If the predicate returns truthy, then its matching output function (mapping function) is provided with the input and, then the result is returned.
Each combination (2-tuple) of predicate + output function should be placed in an array of size 2: [ predicate, mapFn ]
These 2-tuples should be put in an outer array.
Parameter struct
A 2D array. Each element of the array should be an array, a 2-tuple, with a Predicate and a mapping/output function
Returns
{function(any): *}
Example 1
// Here's a 2-tuple where the first element is the isString predicate// and the second element is a function that returns a description of the inputlet firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];// Second tuple: predicate "isNumber", mapfn returns a descriptionlet secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];let third = [ (input) => input === null, (input) => `Oh, null...` ];let fourth = [ (input) => input === undefined, (input) => `notdefined` ];let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);console.log(descriptionOf(undefined)); // 'notdefined'console.log(descriptionOf(55)); // '(55) That's a number!'console.log(descriptionOf("foo")); // 'Here's your string foo'
function pick
pick: (obj: Obj, propNames: string[]) => Obj;
Return a copy of the object only containing the whitelisted properties.
#### Example:
var foo = { a: 1, b: 2, c: 3 };var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }Parameter obj
the source object
Parameter propNames
an Array of strings, which are the whitelisted property names
function pipe
pipe: (...funcs: Function[]) => (obj: any) => any;
Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right given: f(x), g(x), h(x) let piped = pipe(f,g,h); then, piped is: h(g(f(x)))
function pluck
pluck: { <T>(collection: Obj[], propName: string): T[]; (collection: { [key: string]: any }, propName: string): { [key: string]: any };};
Given an array of objects, maps each element to a named property of the element.
Given an object, maps each property of the object to a named property of the property.
function prop
prop: (name: string) => (obj: any) => any;
Given a property name, returns a function that returns that property from an object let obj = { foo: 1, name: "blarg" }; let getName = prop("name"); getName(obj) === "blarg"
function pushR
pushR: (arr: any[], obj: any) => any[];
Reduce function that pushes an object to an array, then returns the array. Mostly just for [[flattenR]] and [[uniqR]]
function pushStateLocationPlugin
pushStateLocationPlugin: (router: UIRouter) => LocationPlugin;
A
UIRouterPlugin
that gets/sets the current location using the browser'slocation
andhistory
apis
function resolvablesBuilder
resolvablesBuilder: (state: StateObject) => Resolvable[];
This is a [[StateBuilder.builder]] function for the
resolve:
block on a [[StateDeclaration]].When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder validates the
resolve
property and converts it to a [[Resolvable]] array.resolve: input value can be:
{ // analyzed but not injected myFooResolve: function() { return "myFooData"; },
// function.toString() parsed, "DependencyName" dep as string (not min-safe) myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },
// Array split; "DependencyName" dep as string myBazResolve: [ "DependencyName", function(dep) { return dep.fetchSomethingAsPromise() },
// Array split; DependencyType dep as token (compared using ===) myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },
// val.$inject used as deps // where: // corgeResolve.$inject = ["DependencyName"]; // function corgeResolve(dep) { dep.fetchSometingAsPromise() } // then "DependencyName" dep as string myCorgeResolve: corgeResolve,
// inject service by name // When a string is found, desugar creating a resolve that injects the named service myGraultResolve: "SomeService" }
or:
[ new Resolvable("myFooResolve", function() { return "myFooData" }), new Resolvable("myBarResolve", function(dep) { return dep.fetchSomethingAsPromise() }, [ "DependencyName" ]), { provide: "myBazResolve", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ "DependencyName" ] } ]
function servicesPlugin
servicesPlugin: (router: UIRouter) => ServicesPlugin;
function silenceUncaughtInPromise
silenceUncaughtInPromise: (promise: Promise<any>) => Promise<any>;
function silentRejection
silentRejection: (error: any) => Promise<any>;
function splitEqual
splitEqual: (str: string) => string[];
function splitHash
splitHash: (str: string) => string[];
function splitOnDelim
splitOnDelim: (delim: string) => (str: string) => string[];
Splits on a delimiter, but returns the delimiters in the array
#### Example:
var splitOnSlashes = splitOnDelim('/');splitOnSlashes("/foo"); // ["/", "foo"]splitOnSlashes("/foo/"); // ["/", "foo", "/"]
function splitQuery
splitQuery: (str: string) => string[];
function stringify
stringify: (o: any) => string;
function stripLastPathElement
stripLastPathElement: (str: string) => string;
function tail
tail: <T>(arr: T[]) => T;
Get the last element of an array
function trimHashVal
trimHashVal: (str: string) => string;
function uniqR
uniqR: <T>(acc: T[], token: T) => T[];
Reduce function that filters out duplicates
function unnest
unnest: (arr: any[]) => any;
Return a new array with a single level of arrays unnested.
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];unnest(input) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
function unnestR
unnestR: (memo: any[], elem: any[]) => any[];
Reduce function which un-nests a single level of arrays
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];input.reduce(unnestR, []) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
function val
val: <T>(v: T) => () => T;
Given a value, returns a function which returns the value
function values
values: <T>(obj: TypedMap<T>) => T[];
Given an object, return its enumerable property values
Example 1
let foo = { a: 1, b: 2, c: 3 }let vals = values(foo); // [ 1, 2, 3 ]
Classes
class BaseLocationServices
abstract class BaseLocationServices implements LocationServices, Disposable {}
A base
LocationServices
constructor
constructor(router: UIRouter, fireAfterUpdate: boolean);
property fireAfterUpdate
fireAfterUpdate: boolean;
property hash
hash: () => any;
property path
path: () => any;
property search
search: () => any;
method dispose
dispose: (router: UIRouter) => void;
method onChange
onChange: (cb: EventListener) => () => Function[];
method url
url: (url?: string, replace?: boolean) => string;
class BrowserLocationConfig
class BrowserLocationConfig implements LocationConfig {}
A
LocationConfig
that delegates to the browser'slocation
object
constructor
constructor(router?: any, _isHtml5?: boolean);
method baseHref
baseHref: (href?: string) => string;
method dispose
dispose: () => void;
method hashPrefix
hashPrefix: () => string;
method host
host: () => string;
method html5Mode
html5Mode: () => boolean;
method port
port: () => number;
method protocol
protocol: () => string;
class Glob
class Glob {}
constructor
constructor(text: string);
property glob
glob: string[];
property regexp
regexp: RegExp;
property text
text: string;
method fromString
static fromString: (text: string) => Glob;
Returns a glob from the string, or null if the string isn't Glob-like
method is
static is: (text: string) => boolean;
Returns true if the string has glob-like characters in it
method matches
matches: (name: string) => boolean;
class HashLocationService
class HashLocationService extends BaseLocationServices {}
A
LocationServices
that uses the browser hash "#" to get/set the current location
constructor
constructor(router: UIRouter);
method dispose
dispose: (router: UIRouter) => void;
class HookBuilder
class HookBuilder {}
This class returns applicable TransitionHooks for a specific Transition instance.
Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g. myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is determined by the type of hook)
The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition.
The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private in the Transition class, so we must also provide the Transition's _treeChanges)
constructor
constructor(transition: Transition);
method buildHooks
buildHooks: (hookType: TransitionEventType) => TransitionHook[];
Returns an array of newly built TransitionHook objects.
- Finds all RegisteredHooks registered for the given
hookType
which matched the transition's [[TreeChanges]]. - Finds [[PathNode]] (orPathNode[]
) to use as the TransitionHook context(s) - For each of the [[PathNode]]s, creates a TransitionHookParameter hookType
the type of the hook registration function, e.g., 'onEnter', 'onFinish'.
method buildHooksForPhase
buildHooksForPhase: (phase: TransitionHookPhase) => TransitionHook[];
method getMatchingHooks
getMatchingHooks: ( hookType: TransitionEventType, treeChanges: TreeChanges, transition: Transition) => RegisteredHook[];
Finds all RegisteredHooks from: - The Transition object instance hook registry - The TransitionService ($transitions) global hook registry
which matched: - the eventType - the matchCriteria (to, from, exiting, retained, entering)
Returns
an array of matched [[RegisteredHook]]s
class MemoryLocationConfig
class MemoryLocationConfig implements LocationConfig {}
A
LocationConfig
mock that gets/sets all config from an in-memory object
class MemoryLocationService
class MemoryLocationService extends BaseLocationServices {}
A
LocationServices
that gets/sets the current location from an in-memory object
constructor
constructor(router: UIRouter);
class Param
class Param {}
constructor
constructor( id: string, type: ParamType, location: DefType, urlConfig: UrlConfig, state: StateDeclaration);
property array
array: boolean;
property config
config: any;
property dynamic
dynamic: boolean;
property id
id: string;
property inherit
inherit: boolean;
property isOptional
isOptional: boolean;
property location
location: DefType;
property raw
raw: boolean;
property replace
replace: [{ to: any; from: any }];
property squash
squash: string | boolean;
property type
type: ParamType;
method changed
static changed: ( params: Param[], values1?: RawParams, values2?: RawParams) => Param[];
Finds [[Param]] objects which have different param values
Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects
Parameter params
: The list of Param objects to filter
Parameter values1
: The first set of parameter values
Parameter values2
: the second set of parameter values
Returns
any Param objects whose values were different between values1 and values2
method equals
static equals: (params: Param[], values1?: {}, values2?: {}) => boolean;
Checks if two param value objects are equal (for a set of [[Param]] objects)
Parameter params
The list of [[Param]] objects to check
Parameter values1
The first set of param values
Parameter values2
The second set of param values
Returns
true if the param values in values1 and values2 are equal
method isDefaultValue
isDefaultValue: (value: any) => boolean;
method isSearch
isSearch: () => boolean;
method toString
toString: () => string;
method validates
static validates: (params: Param[], values?: RawParams) => boolean;
Returns true if a the parameter values are valid, according to the Param definitions
method value
value: (value?: any) => any;
[Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the default value, which may be the result of an injectable function.
method values
static values: (params: Param[], values?: RawParams) => RawParams;
class ParamFactory
class ParamFactory {}
constructor
constructor(router: UIRouter);
method fromConfig
fromConfig: (id: string, type: ParamType, state: StateDeclaration) => Param;
method fromPath
fromPath: (id: string, type: ParamType, state: StateDeclaration) => Param;
method fromSearch
fromSearch: (id: string, type: ParamType, state: StateDeclaration) => Param;
class ParamType
class ParamType implements ParamTypeDefinition {}
An internal class which implements [[ParamTypeDefinition]].
A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types. When a param type definition is registered, an instance of this class is created internally.
This class has naive implementations for all the [[ParamTypeDefinition]] methods.
Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values.
#### Example:
var paramTypeDef = {decode: function(val) { return parseInt(val, 10); },encode: function(val) { return val && val.toString(); },equals: function(a, b) { return this.is(a) && a === b; },is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; },pattern: /\d+/}var paramType = new ParamType(paramTypeDef);
constructor
constructor(def: ParamTypeDefinition);
Parameter def
A configuration object which contains the custom type definition. The object's properties will override the default methods and/or pattern in
ParamType
's public interface.Returns
a new ParamType object
property dynamic
dynamic: boolean;
property inherit
inherit: boolean;
property name
name: string;
The name/id of the parameter type
property pattern
pattern: RegExp;
property raw
raw: boolean;
method $asArray
$asArray: (mode: boolean | 'auto', isSearch: boolean) => any;
Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'. e.g.: - urlmatcher pattern "/path?{queryParam[]:int}" - url: "/path?queryParam=1&queryParam=2 - $stateParams.queryParam will be [1, 2] if
mode
is "auto", then - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
method $normalize
$normalize: (val: any) => any;
Given an encoded string, or a decoded object, returns a decoded object
method $subPattern
$subPattern: () => string;
method decode
decode: (val: string, key?: string) => any;
method encode
encode: (val: any, key?: string) => string | string[];
method equals
equals: (a: any, b: any) => boolean;
method is
is: (val: any, key?: string) => boolean;
method toString
toString: () => string;
class ParamTypes
class ParamTypes {}
A registry for parameter types.
This registry manages the built-in (and custom) parameter types.
The built-in parameter types are:
- [[string]] - [[path]] - [[query]] - [[hash]] - [[int]] - [[bool]] - [[date]] - [[json]] - [[any]]
To register custom parameter types, use [[UrlConfig.type]], i.e.,
router.urlService.config.type(customType)
constructor
constructor();
property any
static any: ParamTypeDefinition;
Built-in parameter type:
any
This parameter type is used by default for url-less parameters (parameters that do not appear in the URL). This type does not encode or decode. It is compared using a deep
equals
comparison.#### Example: This example defines a non-url parameter on a [[StateDeclaration]].
.state({name: 'new',url: '/new',params: {inrepyto: null}});$state.go('new', { inreplyto: currentMessage });
property bool
static bool: ParamTypeDefinition;
Built-in parameter type:
bool
This parameter type serializes
true
/false
as1
/0
#### Example:
.state({name: 'inbox',url: '/inbox?{unread:bool}'});$state.go('inbox', { unread: true });The URL will serialize to:
/inbox?unread=1
.Conversely, if the url is
/inbox?unread=0
, the value of theunread
parameter will be afalse
.
property date
static date: ParamTypeDefinition;
Built-in parameter type:
date
This parameter type can be used to serialize Javascript dates as parameter values.
#### Example:
.state({name: 'search',url: '/search?{start:date}'});$state.go('search', { start: new Date(2000, 0, 1) });The URL will serialize to:
/search?start=2000-01-01
.Conversely, if the url is
/search?start=2016-12-25
, the value of thestart
parameter will be aDate
object where:-
date.getFullYear() === 2016
-date.getMonth() === 11
(month is 0-based) -date.getDate() === 25
property enqueue
enqueue: boolean;
property hash
static hash: ParamTypeDefinition;
Built-in parameter type:
hash
This parameter type is used for the
#
parameter (the hash) It behaves the same as the [[string]] parameter type.
property int
static int: ParamTypeDefinition;
Built-in parameter type:
int
This parameter type serializes javascript integers (
number
s which represent an integer) to the URL.#### Example:
.state({name: 'user',url: '/user/{id:int}'});$state.go('user', { id: 1298547 });The URL will serialize to:
/user/1298547
.When the parameter value is read, it will be the
number
1298547
, not the string"1298547"
.
property json
static json: ParamTypeDefinition;
Built-in parameter type:
json
This parameter type can be used to serialize javascript objects into the URL using JSON serialization.
#### Example: This example serializes an plain javascript object to the URL
.state({name: 'map',url: '/map/{coords:json}'});$state.go('map', { coords: { x: 10399.2, y: 49071 });The URL will serialize to:
/map/%7B%22x%22%3A10399.2%2C%22y%22%3A49071%7D
property path
static path: ParamTypeDefinition;
Built-in parameter type:
path
This parameter type is the default type for path parameters. A path parameter is any parameter declared in the path portion of a url
-
/foo/:param1/:param2
: two path parametersThis parameter type behaves exactly like the [[string]] type with one exception. When matching parameter values in the URL, the
path
type does not match forward slashes/
.#### Angular 1 note: In ng1, this type is overridden with one that pre-encodes slashes as
~2F
instead of%2F
. For more details about this angular 1 behavior, see: https://github.com/angular-ui/ui-router/issues/2598
property query
static query: ParamTypeDefinition;
Built-in parameter type:
query
This parameter type is the default type for query/search parameters. It behaves the same as the [[string]] parameter type.
A query parameter is any parameter declared in the query/search portion of a url
-
/bar?param2
: a query parameter
property string
static string: ParamTypeDefinition;
Built-in parameter type:
string
This parameter type coerces values to strings. It matches anything (
new RegExp(".*")
) in the URL
property typeQueue
typeQueue: any[];
property types
types: any;
method dispose
dispose: () => void;
method type
type: ( name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) => any;
Registers a parameter type
End users should call [[UrlMatcherFactory.type]], which delegates to this method.
class PathNode
class PathNode {}
A node in a [[TreeChanges]] path
For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path. Each PathNode corresponds to a state being entered, exited, or retained. The stateful information includes parameter values and resolve data.
constructor
constructor(node: PathNode);
Creates a copy of a PathNode
constructor
constructor(state: StateObject);
Creates a new (empty) PathNode for a State
property clone
static clone: (node: PathNode) => PathNode;
Returns a clone of the PathNode
Deprecated
use instance method
node.clone()
property paramSchema
paramSchema: Param[];
The parameters declared on the state
property paramValues
paramValues: { [key: string]: any };
The parameter values that belong to the state
property resolvables
resolvables: Resolvable[];
The individual (stateful) resolvable objects that belong to the state
property state
state: StateObject;
The state being entered, exited, or retained
property views
views: ViewConfig[];
The state's declared view configuration objects
method applyRawParams
applyRawParams: (params: RawParams) => PathNode;
Sets [[paramValues]] for the node, from the values of an object hash
method clone
clone: () => PathNode;
method diff
diff: (node: PathNode, paramsFn?: GetParamsFn) => Param[] | false;
Finds Params with different parameter values on another PathNode.
Given another node (of the same state), finds the parameter values which differ. Returns the [[Param]] (schema objects) whose parameter values differ.
Given another node for a different state, returns
false
Parameter node
The node to compare to
Parameter paramsFn
A function that returns which parameters should be compared.
Returns
The [[Param]]s which differ, or null if the two nodes are for different states
method equals
equals: (node: PathNode, paramsFn?: GetParamsFn) => boolean;
Returns
true if the state and parameter values for another PathNode are equal to the state and param values for this PathNode
method parameter
parameter: (name: string) => Param;
Gets a specific [[Param]] metadata that belongs to the node
class PathUtils
class PathUtils {}
This class contains functions which convert TargetStates, Nodes and paths from one type to another.
property nonDynamicParams
static nonDynamicParams: (node: PathNode) => Param[];
property paramValues
static paramValues: (path: PathNode[]) => any;
Gets the raw parameter values from a path
method applyViewConfigs
static applyViewConfigs: ( $view: ViewService, path: PathNode[], states: StateObject[]) => void;
Creates ViewConfig objects and adds to nodes.
On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state
method buildPath
static buildPath: (targetState: TargetState) => PathNode[];
method buildToPath
static buildToPath: ( fromPath: PathNode[], targetState: TargetState) => PathNode[];
Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[]
method equals
static equals: ( pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn) => boolean;
Returns true if two paths are identical.
Parameter pathA
Parameter pathB
Parameter paramsFn
a function which returns the parameters to consider when comparing
Returns
true if the the states and parameter values for both paths are identical
method inheritParams
static inheritParams: ( fromPath: PathNode[], toPath: PathNode[], toKeys?: string[]) => PathNode[];
Given a fromPath and a toPath, returns a new to path which inherits parameters from the fromPath
For a parameter in a node to be inherited from the from path: - The toPath's node must have a matching node in the fromPath (by state). - The parameter name must not be found in the toKeys parameter array.
Note: the keys provided in toKeys are intended to be those param keys explicitly specified by some caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams, it is not inherited from the fromPath.
method makeTargetState
static makeTargetState: ( registry: StateRegistry, path: PathNode[]) => TargetState;
Given a PathNode[], create an TargetState
method matching
static matching: ( pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn) => PathNode[];
Returns a new path which is: the subpath of the first path which matches the second path.
The new path starts from root and contains any nodes that match the nodes in the second path. It stops before the first non-matching node.
Nodes are compared using their state property and their parameter values. If a
paramsFn
is provided, only the [[Param]] returned by the function will be considered when comparing nodes.Parameter pathA
the first path
Parameter pathB
the second path
Parameter paramsFn
a function which returns the parameters to consider when comparing
Returns
an array of PathNodes from the first path which match the nodes in the second path
method subPath
static subPath: (path: PathNode[], predicate: Predicate<PathNode>) => PathNode[];
Return a subpath of a path, which stops at the first matching node
Given an array of nodes, returns a subset of the array starting from the first node, stopping when the first node matches the predicate.
Parameter path
a path of [[PathNode]]s
Parameter predicate
a [[Predicate]] fn that matches [[PathNode]]s
Returns
a subpath up to the matching node, or undefined if no match is found
method treeChanges
static treeChanges: ( fromPath: PathNode[], toPath: PathNode[], reloadState: StateObject) => TreeChanges;
Computes the tree changes (entering, exiting) between a fromPath and toPath.
class PushStateLocationService
class PushStateLocationService extends BaseLocationServices {}
A
LocationServices
that gets/sets the current location using the browser'slocation
andhistory
apisUses
history.pushState
andhistory.replaceState
constructor
constructor(router: UIRouter);
method dispose
dispose: (router: UIRouter) => void;
class Queue
class Queue<T> {}
constructor
constructor(_items?: T[], _limit?: number);
property onEvict
onEvict: (val: (item: T) => void) => (item: T) => void;
method clear
clear: () => Array<T>;
method dequeue
dequeue: () => T;
method enqueue
enqueue: (item: T) => T;
method evict
evict: () => T;
method peekHead
peekHead: () => T;
method peekTail
peekTail: () => T;
method remove
remove: (item: T) => T;
method size
size: () => number;
class RegisteredHook
class RegisteredHook {}
The registration data for a registered transition hook
constructor
constructor( tranSvc: TransitionService, eventType: TransitionEventType, callback: HookFn, matchCriteria: HookMatchCriteria, removeHookFromRegistry: (hook: RegisteredHook) => void, options?: HookRegOptions);
property bind
bind: any;
property callback
callback: HookFn;
property eventType
eventType: TransitionEventType;
property invokeCount
invokeCount: number;
property invokeLimit
invokeLimit: number;
property matchCriteria
matchCriteria: HookMatchCriteria;
property priority
priority: number;
property removeHookFromRegistry
removeHookFromRegistry: (hook: RegisteredHook) => void;
property tranSvc
tranSvc: TransitionService;
method deregister
deregister: () => void;
method matches
matches: (treeChanges: TreeChanges, transition: Transition) => IMatchingNodes;
Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]]
Returns
an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering)
class Rejection
class Rejection {}
constructor
constructor(type: number, message?: string, detail?: any);
property detail
detail: any;
A detail object
This value varies based on the mechanism for rejecting the transition. For example, if an error was thrown from a hook, the
detail
will be theError
object. If a hook returned a rejected promise, thedetail
will be the rejected value.
property message
message: string;
A message describing the rejection
property redirected
redirected: boolean;
Indicates if the transition was redirected.
When a transition is redirected, the rejection [[type]] will be [[RejectType.SUPERSEDED]] and this flag will be true.
property type
type: RejectType;
The type of the rejection.
This value is an number representing the type of transition rejection. If using Typescript, this is a Typescript enum.
- [[RejectType.SUPERSEDED]] (
2
) - [[RejectType.ABORTED]] (3
) - [[RejectType.INVALID]] (4
) - [[RejectType.IGNORED]] (5
) - [[RejectType.ERROR]] (6
)
method aborted
static aborted: (detail?: any) => Rejection;
Returns a Rejection due to aborted transition
method errored
static errored: (detail?: any) => Rejection;
Returns a Rejection due to aborted transition
method ignored
static ignored: (detail?: any) => Rejection;
Returns a Rejection due to ignored transition
method invalid
static invalid: (detail?: any) => Rejection;
Returns a Rejection due to invalid transition
method isRejectionPromise
static isRejectionPromise: (obj: any) => boolean;
Returns true if the obj is a rejected promise created from the
asPromise
factory
method normalize
static normalize: (detail?: Rejection | Error | any) => Rejection;
Returns a Rejection
Normalizes a value as a Rejection. If the value is already a Rejection, returns it. Otherwise, wraps and returns the value as a Rejection (Rejection type: ERROR).
Returns
detail
if it is already aRejection
, else returns an ERROR Rejection.
method redirected
static redirected: (detail?: any) => Rejection;
Returns a Rejection due to redirected transition
method superseded
static superseded: (detail?: any, options?: any) => Rejection;
Returns a Rejection due to transition superseded
method toPromise
toPromise: () => Promise<any>;
method toString
toString: () => string;
class Resolvable
class Resolvable implements ResolvableLiteral {}
The basic building block for the resolve system.
Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise), and the unwrapped-when-complete (.data) result of the resolveFn.
Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the resolveFn) and returns the resulting promise.
Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first parameter to those fns.
constructor
constructor(resolvable: Resolvable);
This constructor creates a Resolvable copy
constructor
constructor(resolvable: ResolvableLiteral);
This constructor creates a new Resolvable from the plain old [[ResolvableLiteral]] javascript object
constructor
constructor( token: any, resolveFn: Function, deps?: any[], policy?: ResolvePolicy, data?: any);
This constructor creates a new
Resolvable
#### Example:
var resolvable1 = new Resolvable('mytoken', http => http.get('foo.json').toPromise(), [Http]);var resolvable2 = new Resolvable(UserService, dep => new UserService(dep.data), [SomeDependency]);var resolvable1Clone = new Resolvable(resolvable1);Parameter token
The new resolvable's injection token, such as
"userList"
(a string) orUserService
(a class). When this token is used during injection, the resolved value will be injected.Parameter resolveFn
The function that returns the resolved value, or a promise for the resolved value
Parameter deps
An array of dependencies, which will be injected into the
resolveFn
Parameter policy
the [[ResolvePolicy]] defines when and how the Resolvable is processed
Parameter data
Pre-resolved data. If the resolve value is already known, it may be provided here.
property data
data: any;
property deps
deps: any[];
property fromData
static fromData: (token: any, data: any) => Resolvable;
property policy
policy: ResolvePolicy;
property promise
promise: Promise<any>;
property resolved
resolved: boolean;
property resolveFn
resolveFn: Function;
property token
token: any;
method clone
clone: () => Resolvable;
method get
get: (resolveContext: ResolveContext, trans?: Transition) => Promise<any>;
Gets a promise for this Resolvable's data.
Fetches the data and returns a promise. Returns the existing promise if it has already been fetched once.
method getPolicy
getPolicy: (state: StateObject) => ResolvePolicy;
method resolve
resolve: (resolveContext: ResolveContext, trans?: Transition) => Promise<any>;
Asynchronously resolve this Resolvable's data
Given a ResolveContext that this Resolvable is found in: Wait for this Resolvable's dependencies, then invoke this Resolvable's function and update the Resolvable's state
method toString
toString: () => string;
class ResolveContext
class ResolveContext {}
Encapsulates Dependency Injection for a path of nodes
UI-Router states are organized as a tree. A nested state has a path of ancestors to the root of the tree. When a state is being activated, each element in the path is wrapped as a [[PathNode]]. A
PathNode
is a stateful object that holds things like parameters and resolvables for the state being activated.The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path.
constructor
constructor(_path: PathNode[]);
method addResolvables
addResolvables: (newResolvables: Resolvable[], state: StateObject) => void;
Adds Resolvables to the node that matches the state
This adds a [[Resolvable]] (generally one created on the fly; not declared on a [[StateDeclaration.resolve]] block). The resolvable is added to the node matching the
state
parameter.These new resolvables are not automatically fetched. The calling code should either fetch them, fetch something that depends on them, or rely on [[resolvePath]] being called when some state is being entered.
Note: each resolvable's [[ResolvePolicy]] is merged with the state's policy, and the global default.
Parameter newResolvables
the new Resolvables
Parameter state
Used to find the node to put the resolvable on
method findNode
findNode: (resolvable: Resolvable) => PathNode;
method getDependencies
getDependencies: (resolvable: Resolvable) => Resolvable[];
Gets the async dependencies of a Resolvable
Given a Resolvable, returns its dependencies as a Resolvable[]
method getPolicy
getPolicy: (resolvable: Resolvable) => ResolvePolicy;
Returns the [[ResolvePolicy]] for the given [[Resolvable]]
method getResolvable
getResolvable: (token: any) => Resolvable;
Gets the Resolvable that matches the token
Gets the last Resolvable that matches the token in this context, or undefined. Throws an error if it doesn't exist in the ResolveContext
method getTokens
getTokens: () => any[];
Gets all the tokens found in the resolve context, de-duplicated
method injector
injector: () => UIInjector;
method resolvePath
resolvePath: ( when?: PolicyWhen, trans?: Transition) => Promise<{ token: any; value: any }[]>;
Returns a promise for an array of resolved path Element promises
Parameter when
Parameter trans
Returns
{Promise|any}
method subContext
subContext: (state: StateObject) => ResolveContext;
Returns a ResolveContext that includes a portion of this one
Given a state, this method creates a new ResolveContext from this one. The new context starts at the first node (root) and stops at the node for the
state
parameter.#### Why
When a transition is created, the nodes in the "To Path" are injected from a ResolveContext. A ResolveContext closes over a path of [[PathNode]]s and processes the resolvables. The "To State" can inject values from its own resolvables, as well as those from all its ancestor state's (node's). This method is used to create a narrower context when injecting ancestor nodes.
Example 1
let ABCD = new ResolveContext([A, B, C, D]);
Given a path
[A, B, C, D]
, whereA
,B
,C
andD
are nodes for statesa
,b
,c
,d
: When injectingD
,D
should have access to all resolvables fromA
,B
,C
,D
. However,B
should only be able to access resolvables fromA
,B
.When resolving for the
B
node, first take the full "To Path" Context[A,B,C,D]
and limit to the subpath[A,B]
.let AB = ABCD.subcontext(a)
class StateBuilder
class StateBuilder {}
A internal global service
StateBuilder is a factory for the internal [[StateObject]] objects.
When you register a state with the [[StateRegistry]], you register a plain old javascript object which conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding [[StateObject]] object, which has an API and is used internally.
Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function using the [[builder]] method.
constructor
constructor(matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory);
method build
build: (state: StateObject) => StateObject;
Builds all of the properties on an essentially blank State object, returning a State object which has all its properties and API built.
Parameter state
an uninitialized State object
Returns
the built State object
method builder
builder: { (property: string, fn: BuilderFunction): Function; (property: string): BuilderFunction | BuilderFunction[];};
Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g.,
parent
,url
, orpath
). More than one BuilderFunction can be registered for a given property.The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.
Parameter property
The name of the State property being registered for.
Parameter fn
The BuilderFunction which will be used to build the State property
Returns
a function which deregisters the BuilderFunction
Gets the registered builder functions for a given property of [[StateObject]].
Parameter property
The name of the State property being registered for.
Returns
the registered builder(s). note: for backwards compatibility, this may be a single builder or an array of builders
method name
name: (state: StateObject) => string;
method parentName
parentName: (state: StateObject) => string;
class StateMatcher
class StateMatcher {}
constructor
constructor(_states: { [key: string]: StateObject });
method find
find: ( stateOrName: StateOrName, base?: StateOrName, matchGlob?: boolean) => StateObject;
method isRelative
isRelative: (stateName: string) => boolean;
method resolvePath
resolvePath: (name: string, base: StateOrName) => string;
class StateObject
class StateObject {}
Internal representation of a UI-Router state.
Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].
A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.
This class prototypally inherits from the corresponding [[StateDeclaration]]. Each of its own properties (i.e.,
hasOwnProperty
) are built using builders from the [[StateBuilder]].
constructor
constructor(config?: StateDeclaration);
Deprecated
use State.create()
property abstract
abstract: boolean;
Prototypally inherits from [[StateDeclaration.abstract]]
property data
data: any;
Prototypally inherits from [[StateDeclaration.data]] Note: This is the only field on the [[StateDeclaration]] which is mutated. The definition object's
data
field is replaced with a new object which prototypally inherits from the parent state definition'sdata
field.
property includes
includes: { [name: string]: boolean };
An object containing the parent States' names as keys and true as their values.
property isState
static isState: (obj: any) => obj is StateObject;
Predicate which returns true if the object is an internal [[StateObject]] object
property isStateClass
static isStateClass: ( stateDecl: _StateDeclaration) => stateDecl is new () => StateDeclaration;
Predicate which returns true if the object is an class with @State() decorator
property isStateDeclaration
static isStateDeclaration: (obj: any) => obj is StateDeclaration;
Predicate which returns true if the object is a [[StateDeclaration]] object
property lazyLoad
lazyLoad: ( transition: Transition, state: StateDeclaration) => Promise<LazyLoadResult>;
Prototypally inherits from [[StateDeclaration.lazyLoad]]
property name
name: string;
The name used to register the state
property navigable
navigable: StateObject;
The nearest parent [[StateObject]] which has a URL
property onEnter
onEnter: TransitionStateHookFn;
Prototypally inherits from [[StateDeclaration.onEnter]]
property onExit
onExit: TransitionStateHookFn;
Prototypally inherits from [[StateDeclaration.onExit]]
property onRetain
onRetain: TransitionStateHookFn;
Prototypally inherits from [[StateDeclaration.onRetain]]
property params
params: { [key: string]: Param };
The parameters for the state, built from the URL and [[StateDeclaration.params]]
property parent
parent: StateObject;
The parent [[StateObject]]
property path
path: StateObject[];
The parent [[StateObject]] objects from this state up to the root
property redirectTo
redirectTo: | string | (($transition$: Transition) => TargetState) | { state: string | StateDeclaration; params: { [key: string]: any } };
Prototypally inherits from [[StateDeclaration.redirectTo]]
property resolvables
resolvables: Resolvable[];
A list of [[Resolvable]] objects. The internal representation of [[resolve]].
property resolve
resolve: any[] | { [key: string]: string | Function | any[] };
Prototypally inherits from [[StateDeclaration.resolve]]
property resolvePolicy
resolvePolicy: any;
Prototypally inherits from [[StateDeclaration.resolvePolicy]]
property self
self: StateDeclaration;
The original [[StateDeclaration]] used to build this [[StateObject]]. Note:
this
object also prototypally inherits from theself
declaration object.
property url
url: UrlMatcher;
A compiled URLMatcher which detects when the state's URL is matched
property views
views: { [key: string]: _ViewDeclaration };
The views for the state. Note:
@uirouter/core
does not register a builder for views. The framework specific code should register aviews
builder.
method create
static create: (stateDecl: _StateDeclaration) => StateObject;
Create a state object to put the private/internal implementation details onto. The object's prototype chain looks like: (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)
Parameter stateDecl
the user-supplied State Declaration
Returns
{StateObject} an internal State object
method fqn
fqn: () => string;
Returns
Returns a dot-separated name of the state.
Deprecated
this does not properly handle dot notation
method is
is: (ref: StateObject | StateDeclaration | string) => boolean;
Returns true if the provided parameter is the same state.
Compares the identity of the state against the passed value, which is either an object reference to the actual
State
instance, the original definition object passed to$stateProvider.state()
, or the fully-qualified name.Parameter ref
Can be one of (a) a
State
instance, (b) an object that was passed into$stateProvider.state()
, (c) the fully-qualified name of a state as a string.Returns
Returns
true
ifref
matches the currentState
instance.
method parameter
parameter: (id: string, opts?: { inherit?: boolean }) => Param;
Returns a single [[Param]] that is owned by the state
If
opts.inherit
is true, it also searches the ancestor states` [[Param]]s.Parameter id
the name of the [[Param]] to return
Parameter opts
options
method parameters
parameters: (opts?: { inherit?: boolean; matchingKeys?: any }) => Param[];
Gets the state's
Param
objectsGets the list of [[Param]] objects owned by the state. If
opts.inherit
is true, it also includes the ancestor states' [[Param]] objects. Ifopts.matchingKeys
exists, returns onlyParam
s whoseid
is a key on thematchingKeys
objectParameter opts
options
method root
root: () => StateObject;
Returns the root node of this state's tree.
Returns
The root of this state's tree.
method toString
toString: () => string;
class StateParams
class StateParams {}
constructor
constructor(params?: Obj);
method $inherit
$inherit: (newParams: Obj, $current: StateObject, $to: StateObject) => any;
Merges a set of parameters with all parameters inherited between the common parents of the current state and a given destination state.
Parameter newParams
The set of parameters which will be composited with inherited params.
Parameter $current
Internal definition of object representing the current state.
Parameter $to
Internal definition of object representing state to transition to.
class StateQueueManager
class StateQueueManager implements Disposable {}
constructor
constructor( router: UIRouter, states: { [key: string]: StateObject }, builder: StateBuilder, listeners: StateRegistryListener[]);
property builder
builder: StateBuilder;
property listeners
listeners: StateRegistryListener[];
property queue
queue: StateObject[];
property states
states: { [key: string]: StateObject };
method attachRoute
attachRoute: (state: StateObject) => void;
method dispose
dispose: () => void;
method flush
flush: () => { [key: string]: StateObject };
method register
register: (stateDecl: _StateDeclaration) => StateObject;
class StateRegistry
class StateRegistry {}
A registry for all of the application's [[StateDeclaration]]s
This API is found at
router.stateRegistry
([[UIRouter.stateRegistry]])
method decorator
decorator: (property: string, builderFunction: BuilderFunction) => Function;
Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g.,
parent
,url
, orpath
). More than one BuilderFunction can be registered for a given property.The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.
Parameter property
The name of the State property being registered for.
Parameter builderFunction
The BuilderFunction which will be used to build the State property
Returns
a function which deregisters the BuilderFunction
method deregister
deregister: (stateOrName: StateOrName) => StateObject[];
Removes a state from the registry
This removes a state from the registry. If the state has children, they are are also removed from the registry.
Parameter stateOrName
the state's name or object representation
Returns
{StateObject[]} a list of removed states
method get
get: { (): StateDeclaration[]; (stateOrName: StateOrName, base?: StateOrName): StateDeclaration;};
Gets all registered states
Calling this method with no arguments will return a list of all the states that are currently registered. Note: this does not return states that are *queued* but not yet registered.
a list of [[StateDeclaration]]s
Gets a registered state
Given a state or a name, finds and returns the [[StateDeclaration]] from the registry. Note: this does not return states that are *queued* but not yet registered.
Parameter stateOrName
either the name of a state, or a state object.
Parameter base
the base state to use when stateOrName is relative. a registered [[StateDeclaration]] that matched the
stateOrName
, or null if the state isn't registered.
method onStatesChanged
onStatesChanged: (listener: StateRegistryListener) => () => void;
Listen for a State Registry events
Adds a callback that is invoked when states are registered or deregistered with the StateRegistry.
#### Example:
let allStates = registry.get();// Later, invoke deregisterFn() to remove the listenerlet deregisterFn = registry.onStatesChanged((event, states) => {switch(event) {case: 'registered':states.forEach(state => allStates.push(state));break;case: 'deregistered':states.forEach(state => {let idx = allStates.indexOf(state);if (idx !== -1) allStates.splice(idx, 1);});break;}});Parameter listener
a callback function invoked when the registered states changes. The function receives two parameters,
event
andstate
. See [[StateRegistryListener]] a function that deregisters the listener
method register
register: (stateDefinition: _StateDeclaration) => StateObject;
Adds a state to the registry
Registers a [[StateDeclaration]] or queues it for registration.
Note: a state will be queued if the state's parent isn't yet registered.
Parameter stateDefinition
the definition of the state to register.
Returns
the internal [[StateObject]] object. If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]). If the state was only queued, then the object is not fully built.
method root
root: () => StateObject;
Gets the implicit root state
Gets the root of the state tree. The root state is implicitly created by UI-Router. Note: this returns the internal [[StateObject]] representation, not a [[StateDeclaration]]
the root [[StateObject]]
class StateService
class StateService {}
Provides services related to ui-router states.
This API is located at
router.stateService
([[UIRouter.stateService]])
property $current
readonly $current: StateObject;
The current [[StateObject]] (an internal API)
Deprecated
This is a passthrough through to [[UIRouterGlobals.$current]]
property current
readonly current: StateDeclaration;
The current [[StateDeclaration]]
Deprecated
This is a passthrough through to [[UIRouterGlobals.current]]
property params
readonly params: StateParams;
The latest successful state parameters
Deprecated
This is a passthrough through to [[UIRouterGlobals.params]]
property transition
readonly transition: Transition;
The [[Transition]] currently in progress (or null)
Deprecated
This is a passthrough through to [[UIRouterGlobals.transition]]
method defaultErrorHandler
defaultErrorHandler: (handler?: (error: any) => void) => (error: any) => void;
Sets or gets the default [[transitionTo]] error handler.
The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition. This includes errors caused by resolves and transition hooks.
Note: This handler does not receive certain Transition rejections. Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].
The built-in default error handler logs the error to the console.
You can provide your own custom handler.
#### Example:
stateService.defaultErrorHandler(function() {// Do not log transitionTo errors});Parameter handler
a global error handler function
Returns
the current global error handler
method get
get: { (stateOrName: StateOrName, base: StateOrName): StateDeclaration; (stateOrName: StateOrName): StateDeclaration; (): StateDeclaration[];};
Gets a registered [[StateDeclaration]] object
Returns the state declaration object for any specific state, or for all registered states.
Parameter stateOrName
(absolute or relative) If provided, will only get the declaration object for the requested state. If not provided, returns an array of ALL states.
Parameter base
When
stateOrName
is a relative state reference (such as.bar.baz
), the state will be retrieved relative to this state.Returns
a [[StateDeclaration]] object (or array of all registered [[StateDeclaration]] objects.)
Deprecated
use [[StateRegistry.get]]
method go
go: ( to: StateOrName, params?: RawParams, options?: TransitionOptions) => TransitionPromise;
Transition to a different state and/or parameters
Convenience method for transitioning to a new state.
$state.go
calls$state.transitionTo
internally but automatically sets options to{ location: true, inherit: true, relative: router.globals.$current, notify: true }
. This allows you to use either an absolute or relativeto
argument (because ofrelative: router.globals.$current
). It also allows you to specify * only the parameters you'd like to update, while letting unspecified parameters inherit from the current parameter values (because ofinherit: true
).#### Example:
let app = angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.changeState = function () {$state.go('contact.detail');};});Parameter to
Absolute state name, state object, or relative state path (relative to current state).
Some examples:
-
$state.go('contact.detail')
- will go to thecontact.detail
state -$state.go('^')
- will go to the parent state -$state.go('^.sibling')
- if current state ishome.child
, will go to thehome.sibling
state -$state.go('.child.grandchild')
- if current state is home, will go to thehome.child.grandchild
stateParameter params
A map of the parameters that will be sent to the state, will populate $stateParams.
Any parameters that are not specified will be inherited from current parameter values (because of
inherit: true
). This allows, for example, going to a sibling state that shares parameters defined by a parent state.Parameter options
Transition options
Returns
{promise} A promise representing the state of the new transition.
method href
href: ( stateOrName: StateOrName, params?: RawParams, options?: HrefOptions) => string;
Generates a URL for a state and parameters
Returns the url for the given state populated with the given params.
#### Example:
expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");Parameter stateOrName
The state name or state object you'd like to generate a url from.
Parameter params
An object of parameter values to fill the state's required parameters.
Parameter options
Options object. The options are:
Returns
{string} compiled state url
method includes
includes: ( stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions) => boolean;
Checks if the current state *includes* the provided state
A method to determine if the current active state is equal to or is the child of the state stateName. If any params are passed then they will be tested for a match as well. Not all the parameters need to be passed, just the ones you'd like to test for equality.
#### Example when
$state.$current.name === 'contacts.details.item'
// Using partial names$state.includes("contacts"); // returns true$state.includes("contacts.details"); // returns true$state.includes("contacts.details.item"); // returns true$state.includes("contacts.list"); // returns false$state.includes("about"); // returns false#### Glob Examples when
* $state.$current.name === 'contacts.details.item.url'
:$state.includes("*.details.*.*"); // returns true$state.includes("*.details.**"); // returns true$state.includes("**.item.**"); // returns true$state.includes("*.details.item.url"); // returns true$state.includes("*.details.*.url"); // returns true$state.includes("*.details.*"); // returns false$state.includes("item.**"); // returns falseParameter stateOrName
A partial name, relative name, glob pattern, or state object to be searched for within the current state name.
Parameter params
A param object, e.g.
{sectionId: section.id}
, that you'd like to test against the current active state.Parameter options
An options object. The options are: -
relative
: IfstateOrName
is a relative state name andoptions.relative
is set, .is will test relative tooptions.relative
state (or name).Returns
{boolean} Returns true if it does include the state
method is
is: ( stateOrName: StateOrName, params?: RawParams, options?: { relative?: StateOrName }) => boolean;
Checks if the current state *is* the provided state
Similar to [[includes]] but only checks for the full state name. If params is supplied then it will be tested for strict equality against the current active params object, so all params must match with none missing and no extras.
#### Example:
$state.$current.name = 'contacts.details.item';// absolute name$state.is('contact.details.item'); // returns true$state.is(contactDetailItemStateObject); // returns true// relative name (. and ^), typically from a template // E.g. from the 'contacts.details' template
<div ng-class="{highlighted: $state.is('.item')}">Item</div>Parameter stateOrName
The state name (absolute or relative) or state object you'd like to check.
Parameter params
A param object, e.g.
{sectionId: section.id}
, that you'd like to test against the current active state.Parameter options
An options object. The options are: -
relative
: IfstateOrName
is a relative state name andoptions.relative
is set, .is will test relative tooptions.relative
state (or name).Returns
Returns true if it is the state.
method lazyLoad
lazyLoad: ( stateOrName: StateOrName, transition?: Transition) => Promise<LazyLoadResult>;
Lazy loads a state
Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.
Parameter stateOrName
the state that should be lazy loaded
Parameter transition
the optional Transition context to use (if the lazyLoad function requires an injector, etc) Note: If no transition is provided, a noop transition is created using the from the current state to the current state. This noop transition is not actually run.
Returns
a promise to lazy load
method onInvalid
onInvalid: (callback: OnInvalidCallback) => Function;
Registers an Invalid State handler
Registers a [[OnInvalidCallback]] function to be invoked when [[StateService.transitionTo]] has been called with an invalid state reference parameter
Example:
stateService.onInvalid(function(to, from, injector) {if (to.name() === 'foo') {let lazyLoader = injector.get('LazyLoadService');return lazyLoader.load('foo').then(() => stateService.target('foo'));}});Parameter callback
invoked when the toState is invalid This function receives the (invalid) toState, the fromState, and an injector. The function may optionally return a [[TargetState]] or a Promise for a TargetState. If one is returned, it is treated as a redirect.
Returns
a function which deregisters the callback
method reload
reload: (reloadState?: StateOrName) => Promise<StateObject>;
Reloads the current state
A method that force reloads the current state, or a partial state hierarchy. All resolves are re-resolved, and components reinstantiated.
#### Example:
let app angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.reload = function(){$state.reload();}});Note:
reload()
is just an alias for:$state.transitionTo($state.current, $state.params, {reload: true, inherit: false});Parameter reloadState
A state name or a state object. If present, this state and all its children will be reloaded, but ancestors will not reload.
#### Example:
//assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'//and current state is 'contacts.detail.item'let app angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.reload = function(){//will reload 'contact.detail' and nested 'contact.detail.item' states$state.reload('contact.detail');}});Returns
A promise representing the state of the new transition. See [[StateService.go]]
method target
target: ( identifier: StateOrName, params?: RawParams, options?: TransitionOptions) => TargetState;
Creates a [[TargetState]]
This is a factory method for creating a TargetState
This may be returned from a Transition Hook to redirect a transition, for example.
method transitionTo
transitionTo: ( to: StateOrName, toParams?: RawParams, options?: TransitionOptions) => TransitionPromise;
Low-level method for transitioning to a new state.
The [[go]] method (which uses
transitionTo
internally) is recommended in most situations.#### Example:
let app = angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.changeState = function () {$state.transitionTo('contact.detail');};});Parameter to
State name or state object.
Parameter toParams
A map of the parameters that will be sent to the state, will populate $stateParams.
Parameter options
Transition options
Returns
A promise representing the state of the new transition. See [[go]]
class TargetState
class TargetState {}
Encapsulate the target (destination) state/params/options of a [[Transition]].
This class is frequently used to redirect a transition to a new destination.
See:
- [[HookResult]] - [[TransitionHookFn]] - [[TransitionService.onStart]]
To create a
TargetState
, use [[StateService.target]].---
This class wraps:
1) an identifier for a state 2) a set of parameters 3) and transition options 4) the registered state object (the [[StateDeclaration]])
Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string). The
TargetState
class normalizes those options.A
TargetState
may be valid (the state being targeted exists in the registry) or invalid (the state being targeted is not registered).
property isDef
static isDef: (obj: any) => obj is TargetStateDef;
Returns true if the object has a state property that might be a state or state name
method $state
$state: () => StateObject;
The internal state object (if it was found)
method error
error: () => string;
If the object is invalid, returns the reason why
method exists
exists: () => boolean;
True if the target state was found
method identifier
identifier: () => StateOrName;
The identifier used when creating this TargetState
method name
name: () => string;
The name of the state this object targets
method options
options: () => TransitionOptions;
The target options
method params
params: () => RawParams;
The target parameter values
method state
state: () => StateDeclaration;
The internal state declaration (if it was found)
method toString
toString: () => string;
method valid
valid: () => boolean;
True if the object is valid
method withOptions
withOptions: (options: TransitionOptions, replace?: boolean) => TargetState;
Returns a copy of this TargetState, using the specified Transition Options.
Parameter options
the new options to use
Parameter replace
When false (default) the new options will be merged with the current options. When true the options will be used instead of the current options.
method withParams
withParams: (params: RawParams, replace?: boolean) => TargetState;
Returns a copy of this TargetState, using the specified parameter values.
Parameter params
the new parameter values to use
Parameter replace
When false (default) the new parameter values will be merged with the current values. When true the parameter values will be used instead of the current values.
method withState
withState: (state: StateOrName) => TargetState;
Returns a copy of this TargetState which targets a different state. The new TargetState has the same parameter values and transition options.
Parameter state
The new state that should be targeted
class Trace
class Trace {}
Prints UI-Router Transition trace information to the console.
method disable
disable: (...categories: (Category | string | number)[]) => any;
Disables a trace [[Category]]
trace.disable("VIEWCONFIG");Parameter categories
categories to disable. If
categories
is omitted, all categories are disabled. Also takes strings (category name) or ordinal (category position)
method enable
enable: (...categories: (Category | string | number)[]) => any;
Enables a trace [[Category]]
trace.enable("TRANSITION");Parameter categories
categories to enable. If
categories
is omitted, all categories are enabled. Also takes strings (category name) or ordinal (category position)
method enabled
enabled: (category: Category | string | number) => boolean;
Retrieves the enabled stateus of a [[Category]]
trace.enabled("VIEWCONFIG"); // true or falseReturns
boolean true if the category is enabled
class Transition
class Transition implements IHookRegistry {}
Represents a transition between two states.
When navigating to a state, we are transitioning **from** the current state **to** the new state.
This object contains all contextual information about the to/from states, parameters, resolves. It has information about all states being entered and exited as a result of the transition.
property $id
$id: number;
A unique identifier for the transition.
This is an auto incrementing integer, starting from
0
.
property isActive
isActive: () => boolean;
Checks if this transition is currently active/running.
property promise
promise: Promise<any>;
This promise is resolved or rejected based on the outcome of the Transition.
When the transition is successful, the promise is resolved When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error
property router
router: UIRouter;
A reference to the [[UIRouter]] instance
This reference can be used to access the router services, such as the [[StateService]]
property success
success: boolean;
A boolean which indicates if the transition was successful
After a successful transition, this value is set to true. After an unsuccessful transition, this value is set to false.
The value will be undefined if the transition is not complete
method abort
abort: () => void;
Aborts this transition
Imperative API to abort a Transition. This only applies to Transitions that are not yet complete.
method addResolvable
addResolvable: ( resolvable: Resolvable | ResolvableLiteral, state?: StateOrName) => void;
Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.
Allows a transition hook to dynamically add a Resolvable to this Transition.
Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).
If a
state
argument is provided, the Resolvable is processed when that state is being entered. If nostate
is provided then the root state is used. If the givenstate
has already been entered, the Resolvable is processed when any child state is entered. If no child states will be entered, the Resolvable is processed during theonFinish
phase of the Transition.The
state
argument also scopes the resolved data. The resolved data is available from the injector for thatstate
and any children states.#### Example:
transitionService.onBefore({}, transition => {transition.addResolvable({token: 'myResolve',deps: ['MyService'],resolveFn: myService => myService.getData()});});Parameter resolvable
a [[ResolvableLiteral]] object (or a [[Resolvable]])
Parameter state
the state in the "to path" which should receive the new resolve (otherwise, the root state)
method dynamic
dynamic: () => boolean;
Returns true if the transition is dynamic.
A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.
Returns
true if the Transition is dynamic
method entering
entering: () => StateDeclaration[];
Gets the states being entered.
Returns
an array of states that will be entered during this transition.
method error
error: () => Rejection;
The Transition error reason.
If the transition is invalid (and could not be run), returns the reason the transition is invalid. If the transition was valid and ran, but was not successful, returns the reason the transition failed.
Returns
a transition rejection explaining why the transition is invalid, or the reason the transition failed.
method exiting
exiting: () => StateDeclaration[];
Gets the states being exited.
Returns
an array of states that will be exited during this transition.
method from
from: () => StateDeclaration;
Returns the "from state"
Returns the state that the transition is coming *from*.
Returns
The state declaration object for the Transition's ("from state").
method getResolveTokens
getResolveTokens: (pathname?: string) => any[];
Gets all available resolve tokens (keys)
This method can be used in conjunction with [[injector]] to inspect the resolve values available to the Transition.
This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states in the Transition's [[TreeChanges.to]] path.
#### Example: This example logs all resolve values
let tokens = trans.getResolveTokens();tokens.forEach(token => console.log(token + " = " + trans.injector().get(token)));#### Example: This example creates promises for each resolve value. This triggers fetches of resolves (if any have not yet been fetched). When all promises have all settled, it logs the resolve values.
let tokens = trans.getResolveTokens();let promise = tokens.map(token => trans.injector().getAsync(token));Promise.all(promises).then(values => console.log("Resolved values: " + values));Note: Angular 1 users whould use
$q.all()
Parameter pathname
resolve context's path name (e.g.,
to
orfrom
)Returns
an array of resolve tokens (keys)
method ignored
ignored: () => boolean;
Returns true if the transition is ignored.
A transition is ignored if no states are entered nor exited, and no parameter values have changed.
Returns
true if the Transition is ignored.
method injector
injector: (state?: StateOrName, pathName?: string) => UIInjector;
Creates a [[UIInjector]] Dependency Injector
Returns a Dependency Injector for the Transition's target state (to state). The injector provides resolve values which the target state has access to.
The
UIInjector
can also provide values from the native root/global injector (ng1/ng2).#### Example:
.onEnter({ entering: 'myState' }, trans => {var myResolveValue = trans.injector().get('myResolve');// Inject a global service from the global/native injector (if it exists)var MyService = trans.injector().get('MyService');})In some cases (such as
onBefore
), you may need access to some resolve data but it has not yet been fetched. You can use [[UIInjector.getAsync]] to get a promise for the data. #### Example:.onBefore({}, trans => {return trans.injector().getAsync('myResolve').then(myResolveValue =>return myResolveValue !== 'ABORT';});});If a
state
is provided, the injector that is returned will be limited to resolve values that the provided state has access to. This can be useful if both a parent statefoo
and a child statefoo.bar
have both defined a resolve such asdata
. #### Example:.onEnter({ to: 'foo.bar' }, trans => {// returns result of `foo` state's `myResolve` resolve// even though `foo.bar` also has a `myResolve` resolvevar fooData = trans.injector('foo').get('myResolve');});If you need resolve data from the exiting states, pass
'from'
aspathName
. The resolve data from thefrom
path will be returned. #### Example:.onExit({ exiting: 'foo.bar' }, trans => {// Gets the resolve value of `myResolve` from the state being exitedvar fooData = trans.injector(null, 'from').get('myResolve');});Parameter state
Limits the resolves provided to only the resolves the provided state has access to.
Parameter pathName
Default:
'to'
: Chooses the path for which to create the injector. Use this to access resolves forexiting
states.Returns
a [[UIInjector]]
method is
is: (compare: Transition | { to?: any; from?: any }) => boolean;
Determines whether two transitions are equivalent.
Deprecated
method onEnter
onEnter: ( criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
method onError
onError: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onExit
onExit: ( criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
method onFinish
onFinish: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onRetain
onRetain: ( criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
method onStart
onStart: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onSuccess
onSuccess: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method options
options: () => TransitionOptions;
Get the transition options
Returns
the options for this Transition.
method originalTransition
originalTransition: () => Transition;
Gets the original transition in a redirect chain
A transition might belong to a long chain of multiple redirects. This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.
#### Example:
// statesregistry.register({ name: 'A', redirectTo: 'B' });registry.register({ name: 'B', redirectTo: 'C' });registry.register({ name: 'C', redirectTo: 'D' });registry.register({ name: 'D' });let transitionA = $state.go('A').transition$transitions.onSuccess({ to: 'D' }, (trans) => {trans.to().name === 'D'; // truetrans.redirectedFrom().to().name === 'C'; // truetrans.originalTransition() === transitionA; // truetrans.originalTransition().to().name === 'A'; // true});Returns
The original Transition that started a redirect chain
method params
params: { (pathname?: string): { [paramName: string]: any }; <T>(pathname?: string): T;};
Gets transition parameter values
Returns the parameter values for a transition as key/value pairs. This object is immutable.
By default, returns the new parameter values (for the "to state").
#### Example:
var toParams = transition.params();To return the previous parameter values, supply
'from'
as thepathname
argument.#### Example:
var fromParams = transition.params('from');Parameter pathname
the name of the treeChanges path to get parameter values for: (
'to'
,'from'
,'entering'
,'exiting'
,'retained'
)Returns
transition parameter values for the desired path.
method paramsChanged
paramsChanged: { (): { [paramName: string]: any }; <T>(): T };
Gets the new values of any parameters that changed during this transition.
Returns any parameter values that have changed during a transition, as key/value pairs.
- Any parameter values that have changed will be present on the returned object reflecting the new value. - Any parameters that *not* have changed will not be present on the returned object. - Any new parameters that weren't present in the "from" state, but are now present in the "to" state will be present on the returned object. - Any previous parameters that are no longer present (because the "to" state doesn't have them) will be included with a value of
undefined
.The returned object is immutable.
#### Examples:
Given:
var stateA = { name: 'stateA', url: '/stateA/:param1/param2' }var stateB = { name: 'stateB', url: '/stateB/:param3' }var stateC = { name: 'stateB.nest', url: '/nest/:param4' }#### Example 1
From
/stateA/abc/def
to/stateA/abc/xyz
var changed = transition.paramsChanged()// changed is { param2: 'xyz' }The value of
param2
changed toxyz
. The value ofparam1
stayed the same so its value is not present.#### Example 2
From
/stateA/abc/def
to/stateB/123
var changed = transition.paramsChanged()// changed is { param1: undefined, param2: undefined, param3: '123' }The value
param3
is present because it is a new param. Bothparam1
andparam2
are no longer present so their value is undefined.#### Example 3
From
/stateB/123
to/stateB/123/nest/456
var changed = transition.paramsChanged()// changed is { param4: '456' }The value
param4
is present because it is a new param. The value ofparam3
did not change, so its value is not present.Returns
an immutable object with changed parameter keys/values.
method redirectedFrom
redirectedFrom: () => Transition;
Gets the transition from which this transition was redirected.
If the current transition is a redirect, this method returns the transition that was redirected.
#### Example:
let transitionA = $state.go('A').transitiontransitionA.onStart({}, () => $state.target('B'));$transitions.onSuccess({ to: 'B' }, (trans) => {trans.to().name === 'B'; // truetrans.redirectedFrom() === transitionA; // true});Returns
The previous Transition, or null if this Transition is not the result of a redirection
method retained
retained: () => StateDeclaration[];
Gets the states being retained.
Returns
an array of states that are already entered from a previous Transition, that will not be exited during this Transition
method targetState
targetState: () => TargetState;
Gets the Target State
A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.
Returns
the [[TargetState]] of this Transition
method to
to: () => StateDeclaration;
Returns the "to state"
Returns the state that the transition is going *to*.
Returns
The state declaration object for the Transition's target state ("to state").
method toString
toString: () => string;
A string representation of the Transition
Returns
A string representation of the Transition
method treeChanges
treeChanges: { (pathname: string): PathNode[]; (): TreeChanges };
Return the transition's tree changes
A transition goes from one state/parameters to another state/parameters. During a transition, states are entered and/or exited.
This function returns various branches (paths) which represent the changes to the active state tree that are caused by the transition.
Parameter pathname
The name of the tree changes path to get: (
'to'
,'from'
,'entering'
,'exiting'
,'retained'
)
method valid
valid: () => boolean;
Checks if the Transition is valid
Returns
true if the Transition is valid
method views
views: (pathname?: string, state?: StateObject) => ViewConfig[];
Get the [[ViewConfig]]s associated with this Transition
Each state can define one or more views (template/controller), which are encapsulated as
ViewConfig
objects. This method fetches theViewConfigs
for a given path in the Transition (e.g., "to" or "entering").Parameter pathname
the name of the path to fetch views for: (
'to'
,'from'
,'entering'
,'exiting'
,'retained'
)Parameter state
If provided, only returns the
ViewConfig
s for a single state in the pathReturns
a list of ViewConfig objects for the given path.
class TransitionEventType
class TransitionEventType {}
This class defines a type of hook, such as
onBefore
oronEnter
. Plugins can define custom hook types, such as sticky states does foronInactive
.
constructor
constructor( name: string, hookPhase: TransitionHookPhase, hookOrder: number, criteriaMatchPath: PathType, reverseSort?: boolean, getResultHandler?: GetResultHandler, getErrorHandler?: GetErrorHandler, synchronous?: boolean);
property criteriaMatchPath
criteriaMatchPath: PathType;
property getErrorHandler
getErrorHandler: GetErrorHandler;
property getResultHandler
getResultHandler: GetResultHandler;
property hookOrder
hookOrder: number;
property hookPhase
hookPhase: TransitionHookPhase;
property name
name: string;
property reverseSort
reverseSort: boolean;
property synchronous
synchronous: boolean;
class TransitionHook
class TransitionHook {}
constructor
constructor( transition: Transition, stateContext: StateDeclaration, registeredHook: RegisteredHook, options: TransitionHookOptions);
property HANDLE_RESULT
static HANDLE_RESULT: GetResultHandler;
These GetResultHandler(s) are used by [[invokeHook]] below Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]])
property LOG_ERROR
static LOG_ERROR: GetErrorHandler;
These GetErrorHandler(s) are used by [[invokeHook]] below Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]])
property LOG_REJECTED_RESULT
static LOG_REJECTED_RESULT: GetResultHandler;
If the result is a promise rejection, log it. Otherwise, ignore the result.
property REJECT_ERROR
static REJECT_ERROR: GetErrorHandler;
property THROW_ERROR
static THROW_ERROR: GetErrorHandler;
property type
type: TransitionEventType;
method chain
static chain: (hooks: TransitionHook[], waitFor?: Promise<any>) => Promise<any>;
Chains together an array of TransitionHooks.
Given a list of [[TransitionHook]] objects, chains them together. Each hook is invoked after the previous one completes.
#### Example:
var hooks: TransitionHook[] = getHooks();let promise: Promise<any> = TransitionHook.chain(hooks);promise.then(handleSuccess, handleError);Parameter hooks
the list of hooks to chain together
Parameter waitFor
if provided, the chain is
.then()
'ed off this promiseReturns
a
Promise
for sequentially invoking the hooks (in order)
method handleHookResult
handleHookResult: (result: HookResult) => Promise<HookResult>;
This method handles the return value of a Transition Hook.
A hook can return false (cancel), a TargetState (redirect), or a promise (which may later resolve to false or a redirect)
This also handles "transition superseded" -- when a new transition was started while the hook was still running
method invokeHook
invokeHook: () => Promise<HookResult> | void;
method invokeHooks
static invokeHooks: <T>( hooks: TransitionHook[], doneCallback: (result?: HookResult) => T) => Promise<any> | T;
Invokes all the provided TransitionHooks, in order. Each hook's return value is checked. If any hook returns a promise, then the rest of the hooks are chained off that promise, and the promise is returned. If no hook returns a promise, then all hooks are processed synchronously.
Parameter hooks
the list of TransitionHooks to invoke
Parameter doneCallback
a callback that is invoked after all the hooks have successfully completed
Returns
a promise for the async result, or the result of the callback
method logError
logError: (err: any) => any;
method runAllHooks
static runAllHooks: (hooks: TransitionHook[]) => void;
Run all TransitionHooks, ignoring their return value.
method toString
toString: () => string;
class TransitionService
class TransitionService implements IHookRegistry, Disposable {}
This class provides services related to Transitions.
- Most importantly, it allows global Transition Hooks to be registered. - It allows the default transition error handler to be set. - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).
At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.
This API is located at
router.transitionService
([[UIRouter.transitionService]])
method onBefore
onBefore: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onEnter
onEnter: ( criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
method onError
onError: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onExit
onExit: ( criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
method onFinish
onFinish: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onRetain
onRetain: ( criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
method onStart
onStart: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
method onSuccess
onSuccess: ( criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
class UIRouter
class UIRouter {}
An instance of UI-Router.
This object contains references to service APIs which define your application's routing behavior.
property globals
globals: UIRouterGlobals;
An object that contains global router state, such as the current state and params
property locationConfig
locationConfig: LocationConfig;
property locationService
locationService: LocationServices;
property stateRegistry
stateRegistry: StateRegistry;
Provides a registry for states, and related registration services
property stateService
stateService: StateService;
Provides services related to states
property trace
trace: Trace;
Enable/disable tracing to the javascript console
property transitionService
transitionService: TransitionService;
A service that exposes global Transition Hooks
property urlMatcherFactory
urlMatcherFactory: UrlMatcherFactory;
Deprecated for public use. Use [[urlService]] instead.
Deprecated
Use [[urlService]] instead
property urlRouter
urlRouter: UrlRouter;
Deprecated for public use. Use [[urlService]] instead.
Deprecated
Use [[urlService]] instead
property urlService
urlService: UrlService;
Provides services related to the URL
property viewService
viewService: ViewService;
Provides services related to ui-view synchronization
method disposable
disposable: (disposable: Disposable) => void;
Registers an object to be notified when the router is disposed
method getPlugin
getPlugin: { (pluginName: string): UIRouterPlugin; (): UIRouterPlugin[] };
Returns a plugin registered with the given
pluginName
.Parameter pluginName
the name of the plugin to get the plugin, or undefined
Returns all registered plugins all registered plugins
method plugin
plugin: { <T extends UIRouterPlugin>( plugin: new (router: UIRouter, options?: any) => T, options?: any ): T; <T extends UIRouterPlugin>( plugin: (router: UIRouter, options?: any) => void, options?: any ): T; <T extends UIRouterPlugin>(plugin: PluginFactory<T>, options?: any): T;};
Add plugin (as ES6 class)
Add plugin (as javascript constructor function)
Add plugin (as javascript factory function)
class UIRouterGlobals
class UIRouterGlobals implements Disposable {}
Global router state
This is where we hold the global mutable state such as current state, current params, current transition, etc.
property current
current: StateDeclaration;
Current state
The to-state from the latest successful transition
property params
params: StateParams;
Current parameter values
The parameter values from the latest successful transition
property transition
transition: Transition;
The current started/running transition. This transition has reached at least the onStart phase, but is not yet complete
method dispose
dispose: () => void;
class UIRouterPluginBase
abstract class UIRouterPluginBase implements UIRouterPlugin, Disposable {}
class UrlConfig
class UrlConfig implements Disposable {}
An API to customize the URL behavior and retrieve URL configuration
This API is used to customize the behavior of the URL. This includes optional trailing slashes ([[strictMode]]), case sensitivity ([[caseInsensitive]]), and custom parameter encoding (custom [[type]]).
It also has information about the location (url) configuration such as [[port]] and [[baseHref]]. This information can be used to build absolute URLs, such as
https://example.com:443/basepath/state/substate?param1=a#hashvalue
;This API is found at
router.urlService.config
(see: [[UIRouter.urlService]], [[URLService.config]])
property baseHref
baseHref: () => string;
Gets the base Href, e.g.,
http://localhost/approot/
the application's base href
property hashPrefix
hashPrefix: (newprefix?: string) => string;
Gets or sets the hashPrefix
This only applies when not running in [[html5Mode]] (pushstate mode)
If the current url is
http://localhost/app#!/uirouter/path/#anchor
, it returns!
which is the prefix for the "hashbang" portion.the hash prefix
property host
host: () => string;
Gets the host, e.g.,
localhost
the protocol
property html5Mode
html5Mode: () => boolean;
Returns true when running in pushstate mode
true when running in html5 mode (pushstate mode).
property port
port: () => number;
Gets the port, e.g.,
80
the port number
property protocol
protocol: () => string;
Gets the protocol, e.g.,
http
the protocol
method caseInsensitive
caseInsensitive: (value?: boolean) => boolean;
Defines whether URL matching should be case sensitive (the default behavior), or not.
#### Example:
// Allow case insensitive url matchesurlService.config.caseInsensitive(true);Parameter value
false
to match URL in a case sensitive manner; otherwisetrue
;Returns
the current value of caseInsensitive
method defaultSquashPolicy
defaultSquashPolicy: (value?: boolean | string) => string | boolean;
Sets the default behavior when generating or matching URLs with default parameter values.
#### Example:
// Remove default parameter values from the urlurlService.config.defaultSquashPolicy(true);Parameter value
A string that defines the default parameter URL squashing behavior. -
nosquash
: When generating an href with a default parameter value, do not squash the parameter value from the URL -slash
: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL - any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string.Returns
the current value of defaultSquashPolicy
method strictMode
strictMode: (value?: boolean) => boolean;
Defines whether URLs should match trailing slashes, or not (the default behavior).
#### Example:
// Allow optional trailing slashesurlService.config.strictMode(false);Parameter value
false
to match trailing slashes in URLs, otherwisetrue
.Returns
the current value of strictMode
method type
type: ( name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) => any;
Creates and registers a custom [[ParamType]] object
A custom parameter type can be used to generate URLs with typed parameters or custom encoding/decoding.
#### Note: Register custom types *before using them* in a state definition.
#### Example:
// Encode object parameter as JSON stringurlService.config.type('myjson', {encode: (obj) => JSON.stringify(obj),decode: (str) => JSON.parse(str),is: (val) => typeof(val) === 'object',pattern: /[^/]+/,equals: (a, b) => _.isEqual(a, b),});See [[ParamTypeDefinition]] for more examples
Parameter name
The type name.
Parameter definition
The type definition. See [[ParamTypeDefinition]] for information on the values accepted.
Parameter definitionFn
A function that is injected before the app runtime starts. The result of this function should be a [[ParamTypeDefinition]]. The result is merged into the existing
definition
. See [[ParamType]] for information on the values accepted.Returns
if only the
name
parameter was specified: the currently registered [[ParamType]] object, or undefined
class UrlMatcher
class UrlMatcher {}
Matches URLs against patterns.
Matches URLs against patterns and extracts named parameters from the path or the search part of the URL.
A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query) parameters. Multiple search parameter names are separated by '&'. Search parameters do not influence whether or not a URL is matched, but their values are passed through into the matched parameters returned by [[UrlMatcher.exec]].
- *Path parameters* are defined using curly brace placeholders (
/somepath/{param}
) or colon placeholders (/somePath/:param
).- *A parameter RegExp* may be defined for a param after a colon (
/somePath/{param:[a-zA-Z0-9]+}
) in a curly brace placeholder. The regexp must match for the url to be matched. Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]].
- *Custom parameter types* may also be specified after a colon (
/somePath/{param:int}
) in curly brace parameters. See [[UrlMatcherFactory.type]] for more information.- *Catch-all parameters* are defined using an asterisk placeholder (
/somepath/*catchallparam
). A catch-all * parameter value will contain the remainder of the URL.---
Parameter names may contain only word characters (latin letters, digits, and underscore) and must be unique within the pattern (across both path and search parameters). A path parameter matches any number of characters other than '/'. For catch-all placeholders the path parameter matches any number of characters.
Examples:
*
'/hello/'
- Matches only if the path is exactly '/hello/'. There is no special treatment for trailing slashes, and patterns have to match the entire path, not just a prefix. *'/user/:id'
- Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or '/user/bob/details'. The second path segment will be captured as the parameter 'id'. *'/user/{id}'
- Same as the previous example, but using curly brace syntax. *'/user/{id:[^/]*}'
- Same as the previous example. *'/user/{id:[0-9a-fA-F]{1,8}}'
- Similar to the previous example, but only matches if the id parameter consists of 1 to 8 hex digits. *'/files/{path:.*}'
- Matches any URL starting with '/files/' and captures the rest of the path into the parameter 'path'. *'/files/*path'
- ditto. *'/calendar/{start:date}'
- Matches "/calendar/2014-11-12" (because the pattern defined in the built-indate
ParamType matches2014-11-12
) and provides a Date object in $stateParams.start
constructor
constructor( pattern: string, paramTypes: ParamTypes, paramFactory: ParamFactory, config?: UrlMatcherCompileConfig);
Parameter pattern
The pattern to compile into a matcher.
Parameter paramTypes
The [[ParamTypes]] registry
Parameter paramFactory
A [[ParamFactory]] object
Parameter config
A [[UrlMatcherCompileConfig]] configuration object
property pattern
pattern: string;
The pattern that was passed into the constructor
method append
append: (url: UrlMatcher) => UrlMatcher;
Creates a new concatenated UrlMatcher
Builds a new UrlMatcher by appending another UrlMatcher to this one.
Parameter url
A
UrlMatcher
instance to append as a child of the currentUrlMatcher
.
method compare
static compare: (a: UrlMatcher, b: UrlMatcher) => number;
Compare two UrlMatchers
This comparison function converts a UrlMatcher into static and dynamic path segments. Each static path segment is a static string between a path separator (slash character). Each dynamic segment is a path parameter.
The comparison function sorts static segments before dynamic ones.
method exec
exec: (path: string, search?: any, hash?: string, options?: any) => RawParams;
Tests the specified url/path against this matcher.
Tests if the given url matches this matcher's pattern, and returns an object containing the captured parameter values. Returns null if the path does not match.
The returned object contains the values of any search parameters that are mentioned in the pattern, but their value may be null if they are not present in
search
. This means that search parameters are always treated as optional.#### Example:
new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {x: '1', q: 'hello'});// returns { id: 'bob', q: 'hello', r: null }Parameter path
The URL path to match, e.g.
$location.path()
.Parameter search
URL search parameters, e.g.
$location.search()
.Parameter hash
URL hash e.g.
$location.hash()
.Parameter options
Returns
The captured parameter values.
method format
format: (values?: RawParams) => string;
Given a set of parameter values, creates a URL from this UrlMatcher.
Creates a URL that matches this pattern by substituting the specified values for the path and search parameters.
#### Example:
new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });// returns '/user/bob?q=yes'Parameter values
the values to substitute for the parameters in this pattern.
Returns
the formatted URL (path and optionally search part).
method toString
toString: () => string;
Returns the input pattern string
method validates
validates: (params: RawParams) => boolean;
Validates the input parameter values against this UrlMatcher
Checks an object hash of parameters to validate their correctness according to the parameter types of this
UrlMatcher
.Parameter params
The object hash of parameters to validate.
Returns
Returns
true
ifparams
validates, otherwisefalse
.
class UrlMatcherFactory
class UrlMatcherFactory {}
Factory for [[UrlMatcher]] instances.
The factory is available to ng1 services as
$urlMatcherFactory
or ng1 providers as$urlMatcherFactoryProvider
.
constructor
constructor(router: UIRouter);
property caseInsensitive
caseInsensitive: (value?: boolean) => boolean;
Deprecated
use [[UrlConfig.caseInsensitive]]
property defaultSquashPolicy
defaultSquashPolicy: (value?: boolean | string) => string | boolean;
Deprecated
use [[UrlConfig.defaultSquashPolicy]]
property Param
Param: typeof Param;
property paramFactory
paramFactory: ParamFactory;
Creates a new [[Param]] for a given location (DefType)
property strictMode
strictMode: (value?: boolean) => boolean;
Deprecated
use [[UrlConfig.strictMode]]
property type
type: ( name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) => any;
Deprecated
use [[UrlConfig.type]]
property UrlMatcher
UrlMatcher: typeof UrlMatcher;
method compile
compile: (pattern: string, config?: UrlMatcherCompileConfig) => UrlMatcher;
Creates a [[UrlMatcher]] for the specified pattern.
Parameter pattern
The URL pattern.
Parameter config
The config object hash.
Returns
The UrlMatcher.
method isMatcher
isMatcher: (object: any) => boolean;
Returns true if the specified object is a [[UrlMatcher]], or false otherwise.
Parameter object
The object to perform the type check against.
Returns
true
if the object matches theUrlMatcher
interface, by implementing all the same methods.
class UrlRouter
class UrlRouter {}
Updates URL and responds to URL changes
### Deprecation warning: This class is now considered to be an internal API Use the [[UrlService]] instead. For configuring URL rules, use the [[UrlRules]] which can be found as [[UrlService.rules]].
property deferIntercept
deferIntercept: (defer?: boolean) => void;
Deprecated
use [[UrlService.deferIntercept]]
property initial
initial: ( handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) => void;
Deprecated
use [[UrlRules.initial]]
property interceptDeferred
readonly interceptDeferred: boolean;
Deprecated
use [[UrlService.interceptDeferred]]
property listen
listen: (enabled?: boolean) => Function;
Deprecated
use [[UrlService.listen]]
property match
match: (urlParts: UrlParts) => MatchResult;
Deprecated
use [[UrlService.match]]
property otherwise
otherwise: ( handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) => void;
Deprecated
use [[UrlRules.otherwise]]
property removeRule
removeRule: (rule: UrlRule) => void;
Deprecated
use [[UrlRules.removeRule]]
property rule
rule: (rule: UrlRule) => Function;
Deprecated
use [[UrlRules.rule]]
property rules
rules: () => UrlRule[];
Deprecated
use [[UrlRules.rules]]
property sort
sort: (compareFn?: (a: UrlRule, b: UrlRule) => number) => void;
Deprecated
use [[UrlRules.sort]]
property sync
sync: (evt?: any) => void;
Deprecated
use [[UrlService.sync]]
property urlRuleFactory
urlRuleFactory: UrlRuleFactory;
used to create [[UrlRule]] objects for common cases
property when
when: ( matcher: RegExp | UrlMatcher | string, handler: string | UrlRuleHandlerFn, options?: { priority: number }) => UrlRule;
Deprecated
use [[UrlRules.when]]
method href
href: ( urlMatcher: UrlMatcher, params?: any, options?: { absolute: boolean }) => string;
Builds and returns a URL with interpolated parameters
#### Example:
matcher = $umf.compile("/about/:person");params = { person: "bob" };$bob = $urlRouter.href(matcher, params);// $bob == "/about/bob";Parameter urlMatcher
The [[UrlMatcher]] object which is used as the template of the URL to generate.
Parameter params
An object of parameter values to fill the matcher's required parameters.
Parameter options
Options object. The options are:
- **
absolute
** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".Returns
Returns the fully compiled URL, or
null
ifparams
fail validation againsturlMatcher
method update
update: (read?: boolean) => void;
Internal API.
class UrlRuleFactory
class UrlRuleFactory {}
Creates a [[UrlRule]]
Creates a [[UrlRule]] from a:
-
string
- [[UrlMatcher]] -RegExp
- [[StateObject]]
constructor
constructor(router: UIRouter);
property isUrlRule
static isUrlRule: (obj: any) => boolean;
property router
router: UIRouter;
method compile
compile: (str: string) => UrlMatcher;
method create
create: ( what: | string | UrlMatcher | StateObject | StateDeclaration | RegExp | UrlRuleMatchFn, handler?: string | UrlRuleHandlerFn) => UrlRule;
method fromRegExp
fromRegExp: (regexp: RegExp, handler: string | UrlRuleHandlerFn) => RegExpRule;
A UrlRule which matches based on a regular expression
The
handler
may be either a [[UrlRuleHandlerFn]] or a string.## Handler as a function
If
handler
is a function, the function is invoked with:- regexp match array (from
regexp
) - url: the current Url ([[UrlParts]]) - router: the router object ([[UIRouter]])#### Example:
var rule = factory.fromRegExp(/^\/foo\/(bar|baz)$/, match => "/home/" + match[1])var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]var result = rule.handler(match); // '/home/bar'## Handler as string
If
handler
is a string, the url is *replaced by the string* when the Rule is invoked. The string is first interpolated usingstring.replace()
style pattern.#### Example:
var rule = factory.fromRegExp(/^\/foo\/(bar|baz)$/, "/home/$1")var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]var result = rule.handler(match); // '/home/bar'
method fromState
fromState: ( stateOrDecl: StateObject | StateDeclaration, router: UIRouter) => StateRule;
A UrlRule which matches a state by its url
#### Example:
var rule = factory.fromState($state.get('foo'), router);var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }var result = rule.handler(match);// Starts a transition to 'foo' with params: { fooId: '123', barId: '456' }
method fromUrlMatcher
fromUrlMatcher: ( urlMatcher: UrlMatcher, handler: string | UrlMatcher | UrlRuleHandlerFn) => MatcherUrlRule;
A UrlRule which matches based on a UrlMatcher
The
handler
may be either astring
, a [[UrlRuleHandlerFn]] or another [[UrlMatcher]]## Handler as a function
If
handler
is a function, the function is invoked with:- matched parameter values ([[RawParams]] from [[UrlMatcher.exec]]) - url: the current Url ([[UrlParts]]) - router: the router object ([[UIRouter]])
#### Example:
var urlMatcher = $umf.compile("/foo/:fooId/:barId");var rule = factory.fromUrlMatcher(urlMatcher, match => "/home/" + match.fooId + "/" + match.barId);var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }var result = rule.handler(match); // '/home/123/456'## Handler as UrlMatcher
If
handler
is a UrlMatcher, the handler matcher is used to create the new url. Thehandler
UrlMatcher is formatted using the matched param from the first matcher. The url is replaced with the result.#### Example:
var urlMatcher = $umf.compile("/foo/:fooId/:barId");var handler = $umf.compile("/home/:fooId/:barId");var rule = factory.fromUrlMatcher(urlMatcher, handler);var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }var result = rule.handler(match); // '/home/123/456'
class UrlRules
class UrlRules implements Disposable {}
API for managing URL rules
This API is used to create and manage URL rules. URL rules are a mechanism to respond to specific URL patterns.
The most commonly used methods are [[otherwise]] and [[when]].
This API is found at
router.urlService.rules
(see: [[UIRouter.urlService]], [[URLService.rules]])
property urlRuleFactory
urlRuleFactory: UrlRuleFactory;
used to create [[UrlRule]] objects for common cases
method initial
initial: ( handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) => void;
Defines the initial state, path, or behavior to use when the app starts.
This rule defines the initial/starting state for the application.
This rule is triggered the first time the URL is checked (when the app initially loads). The rule is triggered only when the url matches either
""
or"/"
.Note: The rule is intended to be used when the root of the application is directly linked to. When the URL is *not*
""
or"/"
and doesn't match other rules, the [[otherwise]] rule is triggered. This allows 404-like behavior when an unknown URL is deep-linked.#### Example: Start app at
home
state..initial({ state: 'home' });#### Example: Start app at
/home
(by url).initial('/home');#### Example: When no other url rule matches, go to
home
state.initial((matchValue, url, router) => {console.log('initial state');return { state: 'home' };})Parameter handler
The initial state or url path, or a function which returns the state or url path (or performs custom logic).
method otherwise
otherwise: ( handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) => void;
Defines the state, url, or behavior to use when no other rule matches the URL.
This rule is matched when *no other rule* matches. It is generally used to handle unknown URLs (similar to "404" behavior, but on the client side).
- If
handler
a string, it is treated as a url redirect#### Example: When no other url rule matches, redirect to
/index
.otherwise('/index');- If
handler
is an object with astate
property, the state is activated.#### Example: When no other url rule matches, redirect to
home
and provide adashboard
parameter value..otherwise({ state: 'home', params: { dashboard: 'default' } });- If
handler
is a function, the function receives the current url ([[UrlParts]]) and the [[UIRouter]] object. The function can perform actions, and/or return a value.#### Example: When no other url rule matches, manually trigger a transition to the
home
state.otherwise((matchValue, urlParts, router) => {router.stateService.go('home');});#### Example: When no other url rule matches, go to
home
state.otherwise((matchValue, urlParts, router) => {return { state: 'home' };});Parameter handler
The url path to redirect to, or a function which returns the url path (or performs custom logic).
method removeRule
removeRule: (rule: any) => void;
Remove a rule previously registered
Parameter rule
the matcher rule that was previously registered using [[rule]]
method rule
rule: (rule: UrlRule) => Function;
Manually adds a URL Rule.
Usually, a url rule is added using [[StateDeclaration.url]] or [[when]]. This api can be used directly for more control (to register a [[BaseUrlRule]], for example). Rules can be created using [[urlRuleFactory]], or created manually as simple objects.
A rule should have a
match
function which returns truthy if the rule matched. It should also have ahandler
function which is invoked if the rule is the best match.a function that deregisters the rule
method rules
rules: () => UrlRule[];
Gets all registered rules
Returns
an array of all the registered rules
method sort
sort: (compareFn?: (a: UrlRule, b: UrlRule) => number) => void;
Defines URL Rule priorities
More than one rule ([[UrlRule]]) might match a given URL. This
compareFn
is used to sort the rules by priority. Higher priority rules should sort earlier.The [[defaultRuleSortFn]] is used by default.
You only need to call this function once. The
compareFn
will be used to sort the rules as each is registered.If called without any parameter, it will re-sort the rules.
---
Url rules may come from multiple sources: states's urls ([[StateDeclaration.url]]), [[when]], and [[rule]]. Each rule has a (user-provided) [[UrlRule.priority]], a [[UrlRule.type]], and a [[UrlRule.$id]] The
$id
is is the order in which the rule was registered.The sort function should use these data, or data found on a specific type of [[UrlRule]] (such as [[StateRule.state]]), to order the rules as desired.
#### Example: This compare function prioritizes rules by the order in which the rules were registered. A rule registered earlier has higher priority.
function compareFn(a, b) {return a.$id - b.$id;}Parameter compareFn
a function that compares to [[UrlRule]] objects. The
compareFn
should abide by theArray.sort
compare function rules. Given two rules,a
andb
, return a negative number ifa
should be higher priority. Return a positive number ifb
should be higher priority. Return0
if the rules are identical.See the [mozilla reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description) for details.
method when
when: ( matcher: RegExp | UrlMatcher | string, handler: string | UrlRuleHandlerFn, options?: { priority: number }) => UrlRule;
Registers a
matcher
andhandler
for custom URLs handling.The
matcher
can be:- a [[UrlMatcher]]: See: [[UrlMatcherFactory.compile]] - a
string
: The string is compiled to a [[UrlMatcher]] - aRegExp
: The regexp is used to match the url.The
handler
can be:- a string: The url is redirected to the value of the string. - a function: The url is redirected to the return value of the function.
---
When the
handler
is astring
and thematcher
is aUrlMatcher
(or string), the redirect string is interpolated with parameter values.#### Example: When the URL is
/foo/123
the rule will redirect to/bar/123
..when("/foo/:param1", "/bar/:param1")---
When the
handler
is a string and thematcher
is aRegExp
, the redirect string is interpolated with capture groups from the RegExp.#### Example: When the URL is
/foo/123
the rule will redirect to/bar/123
..when(new RegExp("^/foo/(.*)$"), "/bar/$1");---
When the handler is a function, it receives the matched value, the current URL, and the
UIRouter
object (See [[UrlRuleHandlerFn]]). The "matched value" differs based on thematcher
. For [[UrlMatcher]]s, it will be the matched state params. ForRegExp
, it will be the match array fromregexp.exec()
.If the handler returns a string, the URL is redirected to the string.
#### Example: When the URL is
/foo/123
the rule will redirect to/bar/123
..when(new RegExp("^/foo/(.*)$"), match => "/bar/" + match[1]);Note: the
handler
may also invoke arbitrary code, such as$state.go()
Parameter matcher
A pattern
string
to match, compiled as a [[UrlMatcher]], or aRegExp
.Parameter handler
The path to redirect to, or a function that returns the path.
Parameter options
{ priority: number }
the registered [[UrlRule]]
class UrlService
class UrlService implements LocationServices, UrlSyncApi {}
API for URL management
property config
config: UrlConfig;
The nested [[UrlConfig]] API to configure the URL and retrieve URL information
See: [[UrlConfig]] for details
property hash
hash: () => string;
Gets the hash part of the current url
If the current URL is
/some/path?query=value#anchor
, this returnsanchor
the hash (anchor) portion of the url
property path
path: () => string;
Gets the path part of the current url
If the current URL is
/some/path?query=value#anchor
, this returns/some/path
the path portion of the url
property rules
rules: UrlRules;
The nested [[UrlRules]] API for managing URL rules and rewrites
See: [[UrlRules]] for details
property search
search: () => { [key: string]: any };
Gets the search part of the current url as an object
If the current URL is
/some/path?query=value#anchor
, this returns{ query: 'value' }
the search (query) portion of the url, as an object
property url
url: (newurl?: string, replace?: boolean, state?: any) => string;
Gets the current url, or updates the url
### Getting the current URL
When no arguments are passed, returns the current URL. The URL is normalized using the internal [[path]]/[[search]]/[[hash]] values.
For example, the URL may be stored in the hash ([[HashLocationServices]]) or have a base HREF prepended ([[PushStateLocationServices]]).
The raw URL in the browser might be:
http://mysite.com/somepath/index.html#/internal/path/123?param1=foo#anchoror
http://mysite.com/basepath/internal/path/123?param1=foo#anchorthen this method returns:
/internal/path/123?param1=foo#anchor#### Example:
locationServices.url(); // "/some/path?query=value#anchor"### Updating the URL
When
newurl
arguments is provided, changes the URL to reflectnewurl
#### Example:
locationServices.url("/some/path?query=value#anchor", true);Parameter newurl
The new value for the URL. This url should reflect only the new internal [[path]], [[search]], and [[hash]] values. It should not include the protocol, site, port, or base path of an absolute HREF.
Parameter replace
When true, replaces the current history entry (instead of appending it) with this new url
Parameter state
The history's state object, i.e., pushState (if the LocationServices implementation supports it)
the url (after potentially being processed)
method deferIntercept
deferIntercept: (defer?: boolean) => void;
Disables monitoring of the URL.
Call this method before UI-Router has bootstrapped. It will stop UI-Router from performing the initial url sync.
This can be useful to perform some asynchronous initialization before the router starts. Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.
#### Example:
// Prevent UI-Router from automatically intercepting URL changes when it starts;urlService.deferIntercept();fetch('/states.json').then(resp => resp.json()).then(data => {data.forEach(state => $stateRegistry.register(state));urlService.listen();urlService.sync();});Parameter defer
Indicates whether to defer location change interception. Passing no parameter is equivalent to
true
.
method listen
listen: (enabled?: boolean) => Function;
Starts or stops listening for URL changes
Call this sometime after calling [[deferIntercept]] to start monitoring the url. This causes UI-Router to start listening for changes to the URL, if it wasn't already listening.
If called with
false
, UI-Router will stop listening (call listen(true) to start listening again).#### Example:
urlService.deferIntercept();fetch('/states.json').then(resp => resp.json()).then(data => {data.forEach(state => $stateRegistry.register(state));// Start responding to URL changesurlService.listen();urlService.sync();});Parameter enabled
true
orfalse
to start or stop listening to URL changes
method match
match: (url: UrlParts) => MatchResult;
Matches a URL
Given a URL (as a [[UrlParts]] object), check all rules and determine the best matching rule. Return the result as a [[MatchResult]].
method parts
parts: () => UrlParts;
Gets the current URL parts
This method returns the different parts of the current URL (the [[path]], [[search]], and [[hash]]) as a [[UrlParts]] object.
method sync
sync: (evt?: any) => void;
Activates the best rule for the current URL
Checks the current URL for a matching [[UrlRule]], then invokes that rule's handler. This method is called internally any time the URL has changed.
This effectively activates the state (or redirect, etc) which matches the current URL.
#### Example:
urlService.deferIntercept();fetch('/states.json').then(resp => resp.json()).then(data => {data.forEach(state => $stateRegistry.register(state));urlService.listen();// Find the matching URL and invoke the handler.urlService.sync();});
class ViewService
class ViewService {}
The View service
This service pairs existing
ui-view
components (which live in the DOM) with view configs (from the state declaration objects: [[StateDeclaration.views]]).- After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]]. The views from exited states are deactivated via [[deactivateViewConfig]]. (See: the [[registerActivateViews]] Transition Hook)
- As
ui-view
components pop in and out of existence, they register themselves using [[registerUIView]].- When the [[sync]] function is called, the registered
ui-view
(s) ([[ActiveUIView]]) are configured with the matching [[ViewConfig]](s)
method activateViewConfig
activateViewConfig: (viewConfig: ViewConfig) => void;
method active
active: () => any[];
Returns the list of views on the page containing loaded content.
{Array} Returns an array of fully-qualified view names.
method available
available: () => any[];
Returns the list of views currently available on the page, by fully-qualified name.
{Array} Returns an array of fully-qualified view names.
method createViewConfig
createViewConfig: (path: PathNode[], decl: _ViewDeclaration) => ViewConfig[];
method deactivateViewConfig
deactivateViewConfig: (viewConfig: ViewConfig) => void;
Deactivates a ViewConfig.
This function deactivates a
ViewConfig
. After calling [[sync]], it will un-pair from anyui-view
with which it is currently paired.Parameter viewConfig
The ViewConfig view to deregister.
method normalizeUIViewTarget
static normalizeUIViewTarget: ( context: ViewContext, rawViewName?: string) => { uiViewName: string; uiViewContextAnchor: string };
Normalizes a view's name from a state.views configuration block.
This should be used by a framework implementation to calculate the values for [[_ViewDeclaration.$uiViewName]] and [[_ViewDeclaration.$uiViewContextAnchor]].
Parameter context
the context object (state declaration) that the view belongs to
Parameter rawViewName
the name of the view, as declared in the [[StateDeclaration.views]]
Returns
the normalized uiViewName and uiViewContextAnchor that the view targets
method registerUIView
registerUIView: (uiView: ActiveUIView) => () => void;
Registers a
ui-view
componentWhen a
ui-view
component is created, it uses this method to register itself. After registration the [[sync]] method is used to ensure allui-view
are configured with the proper [[ViewConfig]].Note: the
ui-view
component uses theViewConfig
to determine what view should be loaded inside theui-view
, and what the view's state context is.Note: There is no corresponding
deregisterUIView
. Aui-view
should hang on to the return value ofregisterUIView
and invoke it to deregister itself.Parameter uiView
The metadata for a UIView a de-registration function used when the view is destroyed.
method sync
sync: () => void;
Interfaces
interface $InjectorLike
interface $InjectorLike {}
interface $QLike
interface $QLike {}
interface $QLikeDeferred
interface $QLikeDeferred {}
interface ActiveUIView
interface ActiveUIView {}
property $type
$type: string;
type of framework, e.g., "ng1" or "ng2"
property config
config: ViewConfig;
The ViewConfig that is currently loaded into the ui-view
property configUpdated
configUpdated: (config: ViewConfig) => void;
A callback that should apply a ViewConfig (or clear the ui-view, if config is undefined)
property creationContext
creationContext: ViewContext;
The state context in which the ui-view tag was created.
property fqn
fqn: string;
The ui-view's fully qualified name
property id
id: number;
An auto-incremented id
property name
name: string;
The ui-view short name
interface CoreServices
interface CoreServices {}
interface CustomAsyncPolicy
interface CustomAsyncPolicy {}
call signature
(data: any): Promise<any>;
interface Disposable
interface Disposable {}
method dispose
dispose: (router?: UIRouter) => any;
Instructs the Disposable to clean up any resources
interface HistoryLike
interface HistoryLike {}
method back
back: (distance?: any) => void;
method forward
forward: (distance?: any) => void;
method pushState
pushState: (statedata: any, title?: string, url?: string) => void;
method replaceState
replaceState: (statedata: any, title?: string, url?: string) => void;
interface HookMatchCriteria
interface HookMatchCriteria {}
This object is used to configure whether or not a Transition Hook is invoked for a particular transition, based on the Transition's "to state" and "from state".
Each property (
to
,from
,exiting
,retained
, andentering
) can be a state [[Glob]] string, a boolean, or a function that takes a state and returns a boolean (see [[HookMatchCriterion]])All properties are optional. If any property is omitted, it is replaced with the value
true
, and always matches. To match any transition, use an empty criteria object{}
.#### Example:
// This matches a transition coming from the `parent` state and going to the `parent.child` state.var match = {to: 'parent',from: 'parent.child'}#### Example:
// This matches a transition coming from any substate of `parent` and going directly to the `parent` state.var match = {to: 'parent',from: 'parent.**'}#### Example:
// This matches a transition coming from any state and going to any substate of `mymodule`var match = {to: 'mymodule.**'}#### Example:
// This matches a transition coming from any state and going to any state that has `data.authRequired`// set to a truthy value.var match = {to: function(state) {return state.data != null && state.data.authRequired === true;}}#### Example:
// This will match when route is just entered (initial load) or when the state is hard-refreshed// by specifying `{refresh: true}` as transition options.var match = {from: (state, transition) => state.self.name === '' || transition.options().reload}#### Example:
// This matches a transition that is exiting `parent.child`var match = {exiting: 'parent.child'}
property entering
entering?: HookMatchCriterion;
A [[HookMatchCriterion]] to match any state that would be entering
property exiting
exiting?: HookMatchCriterion;
A [[HookMatchCriterion]] to match any state that would be exiting
property from
from?: HookMatchCriterion;
A [[HookMatchCriterion]] to match the original (from) state
property retained
retained?: HookMatchCriterion;
A [[HookMatchCriterion]] to match any state that would be retained
property to
to?: HookMatchCriterion;
A [[HookMatchCriterion]] to match the destination state
index signature
[key: string]: HookMatchCriterion | undefined;
interface HookRegOptions
interface HookRegOptions {}
These options may be provided when registering a Transition Hook (such as
onStart
)
property bind
bind?: any;
Specifies what
this
is bound to during hook invocation.
property invokeLimit
invokeLimit?: number;
Limits the number of times that the hook will be invoked. Once the hook has been invoked this many times, it is automatically deregistered.
property priority
priority?: number;
Sets the priority of the registered hook
Hooks of the same type (onBefore, onStart, etc) are invoked in priority order. A hook with a higher priority is invoked before a hook with a lower priority.
The default hook priority is 0
interface HrefOptions
interface HrefOptions {}
An options object for [[StateService.href]]
property absolute
absolute?: boolean;
If true will generate an absolute url, e.g.
http://www.example.com/fullurl
.
property inherit
inherit?: boolean;
If
true
will inherit parameters from the current parameter values.
property lossy
lossy?: boolean;
If true, and if there is no url associated with the state provided in the first parameter, then the constructed href url will be built from the first ancestor which has a url.
property relative
relative?: StateOrName;
Defines what state to be "relative from"
When a relative path is found (e.g
^
or.bar
), defines which state to be relative from.
interface IHookRegistry
interface IHookRegistry {}
This interface specifies the api for registering Transition Hooks. Both the [[TransitionService]] and also the [[Transition]] object itself implement this interface. Note: the Transition object only allows hooks to be registered before the Transition is started.
method getHooks
getHooks: (hookName: string) => RegisteredHook[];
Returns all the registered hooks of a given
hookName
type#### Example:
$transitions.getHooks("onEnter")
method onBefore
onBefore: ( matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionHookFn]], called *before a transition starts*.
Registers a transition lifecycle hook, which is invoked before a transition even begins. This hook can be useful to implement logic which prevents a transition from even starting, such as authentication, redirection
See [[TransitionHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for. To match all Transitions, use an empty criteria object
{}
.### Lifecycle
onBefore
hooks are invoked *before a Transition starts*. No resolves have been fetched yet. EachonBefore
hook is invoked synchronously, in the same call stack as [[StateService.transitionTo]]. The registeredonBefore
hooks are invoked in priority order.Note: during the
onBefore
phase, additional hooks can be added to the specific [[Transition]] instance. These "on-the-fly" hooks only affect the currently running transition..### Return value
The hook's return value can be used to pause, cancel, or redirect the current Transition. See [[HookResult]] for more information.
If any hook modifies the transition *synchronously* (by throwing, returning
false
, or returning a [[TargetState]]), the remainder of the hooks are skipped. If a hook returns a promise, the remainder of theonBefore
hooks are still invoked synchronously. All promises are resolved, and processed asynchronously before theonStart
phase of the Transition.### Examples
#### Default Substate
This example redirects any transition from 'home' to 'home.dashboard'. This is commonly referred to as a "default substate".
Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be invoked.
Returns
a function which deregisters the hook.
Example 1
// ng2transitionService.onBefore({ to: 'home' }, (trans: Transition) =>trans.router.stateService.target("home.dashboard"));#### Data Driven Default Substate
This example provides data-driven default substate functionality. It matches on a transition to any state which has
defaultSubstate: "some.sub.state"
defined. See: [[Transition.to]] which returns the "to state" definition.Example 2
// ng1// state declaration{name: 'home',template: '<div ui-view/>',defaultSubstate: 'home.dashboard'}var criteria = {to: function(state) {return state.defaultSubstate != null;}}$transitions.onBefore(criteria, function(trans: Transition) {var substate = trans.to().defaultSubstate;return trans.router.stateService.target(substate);});#### Require authentication
This example cancels a transition to a state which requires authentication, if the user is not currently authenticated.
This example assumes a state tree where all states which require authentication are children of a parent
'requireauth'
state. This example assumesMyAuthService
synchronously returns a boolean fromisAuthenticated()
.#### Example:
// ng1$transitions.onBefore( { to: 'requireauth.**' }, function(trans) {var myAuthService = trans.injector().get('MyAuthService');// If isAuthenticated returns false, the transition is cancelled.return myAuthService.isAuthenticated();});
method onEnter
onEnter: ( matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionStateHookFn]], called when a specific state is entered.
Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being entered.
Since this hook is run only when the specific state is being *entered*, it can be useful for performing tasks when entering a submodule/feature area such as initializing a stateful service, or for guarding access to a submodule/feature area.
See [[TransitionStateHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.
onEnter
hooks generally specify{ entering: 'somestate' }
. To match all Transitions, use an empty criteria object{}
.### Lifecycle
onEnter
hooks are invoked when the Transition is entering a state. States are entered after theonRetain
phase is complete. If more than one state is being entered, the parent state is entered first. The registeredonEnter
hooks for a state are invoked in priority order.Note: A built-in
onEnter
hook with high priority is used to fetch lazy resolve data for states being entered.### Return value
The hook's return value can be used to pause, cancel, or redirect the current Transition. See [[HookResult]] for more information.
### Inside a state declaration
Instead of registering
onEnter
hooks using the [[TransitionService]], you may define anonEnter
hook directly on a state declaration (see: [[StateDeclaration.onEnter]]).### Examples
#### Audit Log
This example uses a service to log that a user has entered the admin section of an app. This assumes that there are substates of the "admin" state, such as "admin.users", "admin.pages", etc.
Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
Example 1
$transitions.onEnter({ entering: 'admin' }, function(transition, state) {var AuditService = trans.injector().get('AuditService');AuditService.log("Entered " + state.name + " module while transitioning to " + transition.to().name);}#### Audit Log (inside a state declaration)
The
onEnter
inside this state declaration is syntactic sugar for the previous Audit Log example.{name: 'admin',component: 'admin',onEnter: function($transition$, $state$) {var AuditService = $transition$.injector().get('AuditService');AuditService.log("Entered " + state.name + " module while transitioning to " + transition.to().name);}}Note: A state declaration's
onEnter
function is injected for Angular 1 only.
method onError
onError: ( matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionHookFn]], called after a transition has errored.
Registers a transition lifecycle hook, which is invoked after a transition has been rejected for any reason.
See [[TransitionHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for. To match all Transitions, use an empty criteria object
{}
.### Lifecycle
The
onError
hooks are chained off the Transition's promise (see [[Transition.promise]]). If a Transition fails, its promise is rejected and theonError
hooks are invoked. TheonError
hooks are invoked in priority order.Since these hooks are run after the transition is over, their return value is ignored.
A transition "errors" if it was started, but failed to complete (for any reason). A *non-exhaustive list* of reasons a transition can error:
- A transition was cancelled because a new transition started while it was still running (
Transition superseded
) - A transition was cancelled by a Transition Hook returning false - A transition was redirected by a Transition Hook returning a [[TargetState]] - A Transition Hook or resolve function threw an error - A Transition Hook returned a rejected promise - A resolve function returned a rejected promiseTo check the failure reason, inspect the return value of [[Transition.error]].
Note:
onError
should be used for targeted error handling, or error recovery. For simple catch-all error reporting, use [[StateService.defaultErrorHandler]].### Return value
Since the Transition is already completed, the hook's return value is ignored
Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
method onExit
onExit: ( matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionStateHookFn]], called when a specific state is exited.
Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being exited.
Since this hook is run only when the specific state is being *exited*, it can be useful for performing tasks when leaving a submodule/feature area such as cleaning up a stateful service, or for preventing the user from leaving a state or submodule until some criteria is satisfied.
See [[TransitionStateHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.
onExit
hooks generally specify{ exiting: 'somestate' }
. To match all Transitions, use an empty criteria object{}
.### Lifecycle
onExit
hooks are invoked when the Transition is exiting a state. States are exited after anyonStart
phase is complete. If more than one state is being exited, the child states are exited first. The registeredonExit
hooks for a state are invoked in priority order.### Return value
The hook's return value can be used to pause, cancel, or redirect the current Transition. See [[HookResult]] for more information.
### Inside a state declaration
Instead of registering
onExit
hooks using the [[TransitionService]], you may define anonExit
hook directly on a state declaration (see: [[StateDeclaration.onExit]]).Note: A state declaration's
onExit
function is injected for Angular 1 only.Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
method onFinish
onFinish: ( matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionHookFn]], called *just before a transition finishes*.
Registers a transition lifecycle hook, which is invoked just before a transition finishes. This hook is a last chance to cancel or redirect a transition.
See [[TransitionHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for. To match all Transitions, use an empty criteria object
{}
.### Lifecycle
onFinish
hooks are invoked after theonEnter
phase is complete. These hooks are invoked just before the transition is "committed". Each hook is invoked in priority order.### Return value
The hook's return value can be used to pause, cancel, or redirect the current Transition. See [[HookResult]] for more information.
Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
method onRetain
onRetain: ( matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionStateHookFn]], called when a specific state is retained/kept.
Registers a lifecycle hook, which is invoked (during a transition) for a specific state that was previously active will remain active (is not being entered nor exited).
This hook is invoked when a state is "retained" or "kept". It means the transition is coming *from* a substate of the retained state *to* a substate of the retained state. This hook can be used to perform actions when the user moves from one substate to another, such as between steps in a wizard.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.
onRetain
hooks generally specify{ retained: 'somestate' }
. To match all Transitions, use an empty criteria object{}
.### Lifecycle
onRetain
hooks are invoked after anyonExit
hooks have been fired. If more than one state is retained, the child states'onRetain
hooks are invoked first. The registeredonRetain
hooks for a state are invoked in priority order.### Return value
The hook's return value can be used to pause, cancel, or redirect the current Transition. See [[HookResult]] for more information.
### Inside a state declaration
Instead of registering
onRetain
hooks using the [[TransitionService]], you may define anonRetain
hook directly on a state declaration (see: [[StateDeclaration.onRetain]]).Note: A state declaration's
onRetain
function is injected for Angular 1 only.Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
method onStart
onStart: ( matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionHookFn]], called when a transition starts.
Registers a transition lifecycle hook, which is invoked as a transition starts running. This hook can be useful to perform some asynchronous action before completing a transition.
See [[TransitionHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for. To match all Transitions, use an empty criteria object
{}
.### Lifecycle
onStart
hooks are invoked asynchronously when the Transition starts running. This happens after theonBefore
phase is complete. At this point, the Transition has not yet exited nor entered any states. The registeredonStart
hooks are invoked in priority order.Note: A built-in
onStart
hook with high priority is used to fetch any eager resolve data.### Return value
The hook's return value can be used to pause, cancel, or redirect the current Transition. See [[HookResult]] for more information.
### Example
#### Login during transition
This example intercepts any transition to a state which requires authentication, when the user is not currently authenticated. It allows the user to authenticate asynchronously, then resumes the transition. If the user did not authenticate successfully, it redirects to the "guest" state, which does not require authentication.
This example assumes: - a state tree where all states which require authentication are children of a parent
'auth'
state. -MyAuthService.isAuthenticated()
synchronously returns a boolean. -MyAuthService.authenticate()
presents a login dialog, and returns a promise which is resolved or rejected, whether or not the login attempt was successful.#### Example:
// ng1$transitions.onStart( { to: 'auth.**' }, function(trans) {var $state = trans.router.stateService;var MyAuthService = trans.injector().get('MyAuthService');// If the user is not authenticatedif (!MyAuthService.isAuthenticated()) {// Then return a promise for a successful login.// The transition will wait for this promise to settlereturn MyAuthService.authenticate().catch(function() {// If the authenticate() method failed for whatever reason,// redirect to a 'guest' state which doesn't require auth.return $state.target("guest");});}});Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
method onSuccess
onSuccess: ( matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions) => Function;
Registers a [[TransitionHookFn]], called after a successful transition completed.
Registers a transition lifecycle hook, which is invoked after a transition successfully completes.
See [[TransitionHookFn]] for the signature of the function.
The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for. To match all Transitions, use an empty criteria object
{}
.### Lifecycle
onSuccess
hooks are chained off the Transition's promise (see [[Transition.promise]]). If the Transition is successful and its promise is resolved, then theonSuccess
hooks are invoked. Since these hooks are run after the transition is over, their return value is ignored. TheonSuccess
hooks are invoked in priority order.### Return value
Since the Transition is already completed, the hook's return value is ignored
Parameter matchCriteria
defines which Transitions the Hook should be invoked for.
Parameter callback
the hook function which will be injected and invoked.
Returns
a function which deregisters the hook.
interface IMatchingNodes
interface IMatchingNodes {}
interface LazyLoadResult
interface LazyLoadResult {}
The return type of a [[StateDeclaration.lazyLoad]] function
If your state has a
lazyLoad
function, it should return a promise. If promise resolves to an object matching this interface, then thestates
array of [[StateDeclaration]] objects will be automatically registered.
property states
states?: StateDeclaration[];
interface LocationConfig
interface LocationConfig extends Disposable {}
Returns low level URL configuration and metadata
This service returns information about the location configuration. This service is primarily used when building URLs (e.g., for
hrefs
)Implementors should pass these through to the underlying URL APIs. The underlying URL mechanism might be browser APIs, framework APIs, or some 3rd party URL management library.
UI-Router Core includes two basic implementations:
- [[BrowserLocationConfig]] - [[MemoryLocationConfig]]
property baseHref
baseHref: UrlConfig['baseHref'];
See: [[UrlConfig.baseHref]]
property hashPrefix
hashPrefix: UrlConfig['hashPrefix'];
See: [[UrlConfig.hashPrefix]]
property host
host: UrlConfig['host'];
See: [[UrlConfig.host]]
property html5Mode
html5Mode: UrlConfig['html5Mode'];
See: [[UrlConfig.html5Mode]]
property port
port: UrlConfig['port'];
See: [[UrlConfig.port]]
property protocol
protocol: UrlConfig['protocol'];
See: [[UrlConfig.protocol]]
interface LocationLike
interface LocationLike {}
interface LocationPlugin
interface LocationPlugin extends UIRouterPlugin {}
property configuration
configuration: LocationConfig;
property service
service: LocationServices;
interface LocationServices
interface LocationServices extends Disposable {}
Handles low level URL read/write
This service handles low level reads and updates of the URL and listens for url changes. Implementors should pass these through to the underlying URL mechanism. The underlying URL mechanism might be browser APIs, framework APIs, or some 3rd party URL management library.
UI-Router Core includes three basic implementations:
- [[PushStateLocationService]] - [[HashLocationService]] - [[MemoryLocationService]]
property hash
hash: UrlService['hash'];
See: [[UrlService.hash]]
property onChange
onChange: UrlService['onChange'];
See: [[UrlService.onChange]]
property path
path: UrlService['path'];
See: [[UrlService.path]]
property search
search: UrlService['search'];
See: [[UrlService.search]]
property url
url: UrlService['url'];
See: [[UrlService.url]]
interface MatcherUrlRule
interface MatcherUrlRule extends UrlRule {}
property type
type: 'URLMATCHER' | 'STATE';
property urlMatcher
urlMatcher: UrlMatcher;
interface MatchResult
interface MatchResult {}
A UrlRule match result
The result of UrlRouter.match()
interface Obj
interface Obj extends Object {}
index signature
[key: string]: any;
interface ParamDeclaration
interface ParamDeclaration {}
Configuration for a single Parameter
In a [[StateDeclaration.params]], each
ParamDeclaration
defines how a single State Parameter should work.#### Example:
var mystate = {template: '<div ui-view/>',controller: function() {}url: '/mystate/:start?{count:int}',params: {start: { // <-- ParamDeclaration for `start`type: 'date',value: new Date(), // <-- Default valuesquash: true,},nonUrlParam: { // <-- ParamDeclaration for 'nonUrlParam'type: "int",array: true,value: []},count: 0, // <-- Default value for 'param1'// (shorthand ParamDeclaration.value)}}
property array
array?: boolean;
The parameter's
array
modeExplicitly specifies the array mode of a URL parameter
- If
false
, the parameter value will be treated (encoded/decoded) as a single value - Iftrue
, the parameter value will be treated (encoded/decoded) as an array of values. - Ifauto
(for query parameters only), if multiple values for a single parameter are present in the URL (e.g.: /foo?bar=1&bar=2&bar=3) then the values are mapped to an array (e.g.:{ foo: [ '1', '2', '3' ] }
). However, if only one value is present (e.g.: /foo?bar=1) then the value is treated as single value (e.g.: { foo: '1' }).If you specified a [[type]] for the parameter, the value will be treated as an array of the specified [[ParamType]].
#### Example:
{name: 'foo',url: '/foo/{arrayParam:int}`,params: {arrayParam: { array: true }}}// After the transition, URL should be '/foo/1-2-3'$state.go("foo", { arrayParam: [ 1, 2, 3 ] });false
for path parameters, such asurl: '/foo/:pathParam'
auto
for query parameters, such asurl: '/foo?queryParam'
true
if the parameter name ends in[]
, such asurl: '/foo/{implicitArrayParam:int[]}'
property dynamic
dynamic?: boolean;
Dynamic flag
When
dynamic
istrue
, changes to the parameter value will not cause the state to be entered/exited. The resolves will not be re-fetched, nor will views be reloaded.Normally, if a parameter value changes, the state which declared that the parameter will be reloaded (entered/exited). When a parameter is
dynamic
, a transition still occurs, but it does not cause the state to exit/enter.This can be useful to build UI where the component updates itself when the param values change. A common scenario where this is useful is searching/paging/sorting.
---
Note: this value overrides the
dynamic
value on a custom parameter type ([[ParamTypeDefinition.dynamic]]).---
Default:
false
property inherit
inherit?: boolean;
Enables/disables inheriting of this parameter's value
When a transition is run with [[TransitionOptions.inherit]] set to
true
, the current param values are inherited in the new transition. However, parameters values which haveinherit: false
set will *not be inherited*.#### Example state :
var fooState = {name: 'foo',url: '/:fooId?mode&refresh',params: {refresh: { inherit: false }}}// Set fooId to 123$state.go('fooState', { fooId: 1234, mode: 'list', refresh: true });In the component: `mode: 'list' is inherited, but refresh: true is not inherited. // The param values are thus:
{ fooId: 4567, mode: 'list' }
<ui-sref="foo({ fooId: 4567 })">4567</ui-sref>---
See also [[TransitionOptions.inherit]] and [[ParamTypeDefinition.inherit]]
---
Default:
true
property raw
raw?: boolean;
Disables url-encoding of parameter values
When
true
, parameter values are not url-encoded. This is commonly used to allow "slug" urls, with a parameter value including non-semantic slashes.#### Example:
url: '/product/:slug',params: {slug: { type: 'string', raw: true }}This allows a URL parameter of
{ slug: 'camping/tents/awesome_tent' }
to serialize to/product/camping/tents/awesome_tent
instead of/product/camping%2Ftents%2Fawesome_tent
.---
Note: this value overrides the
raw
value on a custom parameter type ([[ParamTypeDefinition.raw]]).### Decoding warning
The decoding behavior of raw parameters is not defined. For example, given a url template such as
/:raw1/:raw2
the url/foo/bar/baz/qux/
, there is no way to determine which slashes belong to which params.It's generally safe to use a raw parameter at the end of a path, like '/product/:slug'. However, beware of the characters you allow in your raw parameter values. Avoid unencoded characters that could disrupt normal URL parsing, such as
?
and#
.---
Default:
false
property squash
squash?: boolean | string;
Squash mode: omit default parameter values in URL
Configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.
There are three squash settings:
-
false
: The parameter's default value is not squashed. It is encoded and included in the URL -true
: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed by slashes in the state's url declaration, then one of those slashes are omitted. This can allow for cleaner looking URLs. -"<arbitrary string>"
: The parameter's default value is replaced with an arbitrary placeholder of your choice.#### Example:
{name: 'mystate',url: '/mystate/:myparam',params: {myparam: 'defaultParamValue'squash: true}}// URL will be `/mystate/`$state.go('mystate', { myparam: 'defaultParamValue' });// URL will be `/mystate/someOtherValue`$state.go('mystate', { myparam: 'someOtherValue' });#### Example:
{name: 'mystate2',url: '/mystate2/:myparam2',params: {myparam2: 'defaultParamValue'squash: "~"}}// URL will be `/mystate/~`$state.go('mystate', { myparam2: 'defaultParamValue' });// URL will be `/mystate/someOtherValue`$state.go('mystate', { myparam2: 'someOtherValue' });Default: If squash is not set, it uses the configured default squash policy. (See [[defaultSquashPolicy]]())
property type
type?: string | ParamType;
The parameter's type
Specifies the [[ParamType]] of the parameter. Parameter types can be used to customize the encoding/decoding of parameter values.
Set this property to the name of parameter's type. The type may be either one of the built in types, or a custom type that has been registered with the [[UrlMatcherFactory]].
See [[ParamTypes]] for the list of built in types.
---
Default: - Path parameters (
/:fooParam
):path
- Query parameters (?queryParam
):query
- Non-url parameters (param: { foo: null }
):any
property value
value?: any;
The default value for this parameter.
Specifies the default value for this parameter. This implicitly sets this parameter as optional.
When UI-Router routes to a state and no value is specified for this parameter in the URL or transition, the default value will be used instead. If value is a function, it will be injected and invoked, and the return value used.
Note:
value: undefined
is treated as though **no default value was specified**, whilevalue: null
is treated as **"the default value is null"**.// define default values for param1 and param2params: {param1: {value: "defaultValue"},param2: {value: "param2Default;}}### Shorthand Declaration
If you only want to set the default value of the parameter, you may use a shorthand syntax. In the params map, instead mapping the param name to a full parameter configuration object, simply set map it to the default parameter value, e.g.:
// Normal (non-shorthand) default value syntaxparams: {param1: {value: "defaultValue"},param2: {value: "param2Default"}}// Shorthand default value syntaxparams: {param1: "defaultValue",param2: "param2Default"}This defines a default value for the parameter. If a parameter value is
undefined
, this default value will be used instead---
Default:
undefined
interface ParamTypeDefinition
interface ParamTypeDefinition {}
Describes a custom [[ParamType]]
See: [[UrlMatcherFactory.type]]
A developer can create a custom parameter type definition to customize the encoding and decoding of parameter values. The definition should implement all the methods of this interface.
Parameter values are parsed from the URL as strings. However, it is often useful to parse the string into some other form, such as:
- integer - date - array of <integer/date/string> - custom object - some internal string representation
Typed parameter definitions control how parameter values are encoded (to the URL) and decoded (from the URL). UI-Router always provides the decoded parameter values to the user (from methods such as [[Transition.params]])).
For example, if a state has a url of
/foo/{fooId:int}
(thefooId
parameter is of theint
ParamType) and if the browser is at/foo/123
, then the 123 is parsed as an integer:var fooId = transition.params().fooId;fooId === "123" // falsefooId === 123 // true#### Examples
This example encodes an array of integers as a dash-delimited string to be used in the URL.
If we call
$state.go('foo', { fooIds: [20, 30, 40] });
, the URL changes to/foo/20-30-40
. If we navigate to/foo/1-2-3
, thefoo
state's onEnter logs[1, 2, 3]
.Example 1
$urlMatcherFactoryProvider.type('intarray', {// Take an array of ints [1,2,3] and return a string "1-2-3"encode: (array) => array.join("-"),// Take an string "1-2-3" and return an array of ints [1,2,3]decode: (str) => str.split("-").map(x => parseInt(x, 10)),// Match the encoded string in the URLpattern: new RegExp("[0-9]+(?:-[0-9]+)*")// Ensure that the (decoded) object is an array, and that all its elements are numbersis: (obj) => Array.isArray(obj) &&obj.reduce((acc, item) => acc && typeof item === 'number', true),// Compare two arrays of integersequals: (array1, array2) => array1.length === array2.length &&array1.reduce((acc, item, idx) => acc && item === array2[idx], true);});$stateProvider.state('foo', {url: "/foo/{fooIds:intarray}",onEnter: function($transition$) {console.log($transition$.fooIds); // Logs "[1, 2, 3]"}});This example decodes an integer from the URL. It uses the integer as an index to look up an item from a static list. That item from the list is the decoded parameter value.
Example 2
var list = ['John', 'Paul', 'George', 'Ringo'];$urlMatcherFactoryProvider.type('listItem', {encode: function(item) {// Represent the list item in the URL using its corresponding indexreturn list.indexOf(item);},decode: function(item) {// Look up the list item by indexreturn list[parseInt(item, 10)];},is: function(item) {// Ensure the item is valid by checking to see that it appears// in the listreturn list.indexOf(item) > -1;}});$stateProvider.state('list', {url: "/list/{item:listItem}",controller: function($scope, $stateParams) {console.log($stateParams.item);}});// ...// Changes URL to '/list/3', logs "Ringo" to the console$state.go('list', { item: "Ringo" });See: [[UrlConfig.type]]
property dynamic
dynamic?: boolean;
Dynamic flag
When
dynamic
istrue
, changes to the parameter value will not cause the state to be entered/exited.Normally, if a parameter value changes, the state which declared that the parameter will be reloaded (entered/exited). When a parameter is
dynamic
, a transition still occurs, but it does not cause the state to exit/enter.Default:
false
property inherit
inherit?: boolean;
Enables/disables inheriting of parameter values (of this type)
When a transition is run with [[TransitionOptions.inherit]] set to
true
, the current param values are inherited in the new transition. However, parameters whose type hasinherit: false
set will *not be inherited*.The internal parameter type of
hash
hasinherit: false
. This is used to disable inheriting of the hash value (#
) on subsequent transitions.#### Example:
$state.go('home', { '#': 'inboxAnchor' });...// "#" is not inherited.// The value of the "#" parameter will be `null`// The url's hash will be cleared.$state.go('home.nest');---
See also [[TransitionOptions.inherit]] and [[ParamDeclaration.inherit]]
property pattern
pattern?: RegExp;
A regular expression that matches the encoded parameter type
This regular expression is used to match an encoded parameter value **in the URL**.
For example, if your type encodes as a dash-separated numbers, match that here:
new RegExp("[0-9]+(?:-[0-9]+)*")
.There are some limitations to these regexps:
- No capturing groups are allowed (use non-capturing groups:
(?: )
) - No pattern modifiers like case insensitive - No start-of-string or end-of-string:/^foo$/
property raw
raw?: boolean;
Disables url-encoding of parameter values
If a parameter type is declared
raw
, it will not be url-encoded. Custom encoding can still be applied in the [[encode]] function.### Decoding warning
The decoding behavior of raw parameters is not defined. See: [[ParamDeclaration.raw]] for details
method decode
decode: (val: string, key?: string) => any;
Decodes a parameter value string (from URL string or transition param) to a custom/native value.
For example, if your type decodes to an array of ints, then decode the string as an array of ints here:
decode: (str) => str.split("-").map(str => parseInt(str, 10))Note: in general, [[encode]] and [[decode]] should be symmetrical. That is,
encode(decode(str)) === str
Parameter val
The URL parameter value to decode.
Parameter key
The name of the parameter in which
val
is stored. Can be used for meta-programming ofParamType
objects.Returns
a custom representation of the URL parameter value.
method encode
encode: (val: any, key?: string) => string | string[];
Encodes a custom/native type value to a string that can be embedded in a URL.
Note that the return value does *not* need to be URL-safe (i.e. passed through
encodeURIComponent()
). It only needs to be a representation ofval
that has been encoded as a string.For example, if your custom type decodes to an array of ints, then encode the array of ints to a string here:
encode: (intarray) => intarray.join("-")Note: in general, [[encode]] and [[decode]] should be symmetrical. That is,
encode(decode(str)) === str
Parameter val
The value to encode.
Parameter key
The name of the parameter in which
val
is stored. Can be used for meta-programming ofParamType
objects.Returns
a string representation of
val
that can be encoded in a URL.
method equals
equals: (a: any, b: any) => boolean;
Determines whether two decoded values are equivalent.
For example, if your type decodes to an array of ints, then check if the arrays are equal:
equals: (a, b) => a.length === b.length && a.reduce((acc, x, idx) => acc && x === b[idx], true)Parameter a
A value to compare against.
Parameter b
A value to compare against.
Returns
true
if the values are equivalent/equal, otherwisefalse
.
method is
is: (val: any, key?: string) => boolean;
Tests if some object type is compatible with this parameter type
Detects whether some value is of this particular type. Accepts a decoded value and determines whether it matches this
ParamType
object.If your custom type encodes the parameter to a specific type, check for that type here. For example, if your custom type decodes the URL parameter value as an array of ints, return true if the input is an array of ints:
is: (val) => Array.isArray(val) && array.reduce((acc, x) => acc && parseInt(val, 10) === val, true)If your type decodes the URL parameter value to a custom string, check that the string matches the pattern (don't use an arrow fn if you need
this
):function (val) { return !!this.pattern.exec(val) }
Note: This method is _not used to check if the URL matches_. It's used to check if a _decoded value *is* this type_. Use [[pattern]] to check the encoded value in the URL.
Parameter val
The value to check.
Parameter key
If the type check is happening in the context of a specific [[UrlMatcher]] object, this is the name of the parameter in which
val
is stored. Can be used for meta-programming ofParamType
objects.Returns
true
if the value matches the type, otherwisefalse
.
interface ProviderLike
interface ProviderLike {}
An interface which is similar to an Angular 2
Provider
property deps
deps?: any[];
property provide
provide: any;
property useClass
useClass?: any;
property useExisting
useExisting?: any;
property useFactory
useFactory?: Function;
property useValue
useValue?: any;
interface RawParams
interface RawParams {}
Parameter values
An object containing state parameter key/value pairs
#### Example:
{userId: 353474,folderId: 'inbox'}
index signature
[key: string]: any;
interface RegExpRule
interface RegExpRule extends UrlRule {}
interface Replace
interface Replace {}
String replacement
Represents an exact match string replacement.
Note:
to
orfrom
may be null or undefined, and will be tested using===
.
interface ResolvableLiteral
interface ResolvableLiteral {}
A plain object used to describe a [[Resolvable]]
These objects may be used in the [[StateDeclaration.resolve]] array to declare async data that the state or substates require.
#### Example:
var state = {name: 'main',resolve: [{ token: 'myData', deps: [MyDataApi], resolveFn: (myDataApi) => myDataApi.getData() },],}
property data
data?: any;
Pre-resolved data.
property deps
deps?: any[];
The Dependency Injection tokens
This is an array of Dependency Injection tokens for the dependencies of the [[resolveFn]].
The DI tokens are references to other
Resolvables
, or to other services from the native DI system.
property policy
policy?: ResolvePolicy;
Defines the Resolve Policy
A policy that defines when to invoke the resolve, and whether to wait for async and unwrap the data
property resolveFn
resolveFn: Function;
A function which fetches the Resolvable's data
A function which returns one of:
- The resolved value (synchronously) - A promise for the resolved value - An Observable of the resolved value(s)
This function will be provided the dependencies listed in [[deps]] as its arguments. The resolve system will asynchronously fetch the dependencies before invoking this function.
property token
token: any;
A Dependency Injection token
This Resolvable's DI token. The Resolvable will be injectable elsewhere using the token.
interface ResolvePolicy
interface ResolvePolicy {}
Defines how a resolve is processed during a transition
This object is the [[StateDeclaration.resolvePolicy]] property.
#### Example:
// Fetched when the resolve's state is being entered.// Wait for the promise to resolve.var policy1 = { when: "LAZY", async: "WAIT" }// Fetched when the Transition is starting.// Do not wait for the returned promise to resolve.// Inject the raw promise/valuevar policy2 = { when: "EAGER", async: "NOWAIT" }The policy for a given Resolvable is merged from three sources (highest priority first):
- 1) Individual resolve definition - 2) State definition - 3) Global default
#### Example:
// Wait for an Observable to emit one item.// Since `wait` is not specified, it uses the `wait`// policy defined on the state, or the global default// if no `wait` policy is defined on the stateimport { RXWAIT } from '@uirouter/rx';var myResolvablePolicy = { async: RXWAIT }
property async
async?: PolicyAsync;
Determines the unwrapping behavior of asynchronous resolve values.
-
WAIT
(default) - If a promise is returned from the resolveFn, wait for the promise before proceeding - The unwrapped value from the promise -NOWAIT
- If a promise is returned from the resolve, do not wait for the promise. - Any other value returned is wrapped in a promise. - The promise will not be unwrapped. - The promise itself will be provided when the resolve is injected or bound elsewhere. - CustomAsyncPolicy - You can define a custom function that will be called with the resolveFn value. - This function must return a promise. - The transition will wait for this promise before proceedingNOTE: The previous
RXWAIT
policy has become a CustomAsyncPolicy function exported in@uirouter/rx
package.#### Example: The
Transition
will not wait for the resolve promise(s) frommain
to settle before continuing. Resolves formain
will be provided to components wrapped in aPromise
.The
Transition
will wait for themain.home
resolve promises. Resolved values will be unwrapped before being provided to components.var mainState = {name: 'main',resolve: mainResolves, // defined elsewhereresolvePolicy: { async: 'NOWAIT' },}var homeState = {name: 'main.home',resolve: homeResolves, // defined elsewhereresolvePolicy: { async: 'WAIT' }, // default}
property when
when?: PolicyWhen;
Defines when a Resolvable is resolved (fetched) during a transition
-
LAZY
(default) - Resolved as the resolve's state is being entered -EAGER
- Resolved as the transition is starting#### Example: Resolves for
main
andmain.home
are fetched when each state is entered. All ofmain
resolves are processed before fetchingmain.home
resolves.var state = {name: 'main',resolve: mainResolves, // defined elsewhereresolvePolicy: { when: 'LAZY' }, // default}var state = {name: 'main.home',resolve: homeResolves, // defined elsewhereresolvePolicy: { when: 'LAZY' }, // default}#### Example: Resolves for
main
andmain.home
are fetched at the same time when the transition starts. This happens earlier in the lifecycle than when states are entered. All of themain
andmain.home
resolves are fetched as soon as possible.var mainState = {name: 'main',resolve: mainResolves, // defined elsewhereresolvePolicy: { when: 'EAGER' },}var homeState = {name: 'main.home',resolve: homeResolves, // defined elsewhereresolvePolicy: { when: 'EAGER' },}
interface ServicesPlugin
interface ServicesPlugin extends UIRouterPlugin {}
interface StateDeclaration
interface StateDeclaration {}
The StateDeclaration object is used to define a state or nested state.
Note: Each implementation of UI-Router (for a specific framework) extends this interface as necessary.
#### Example:
// StateDeclaration objectvar foldersState = {name: 'folders',url: '/folders',component: FoldersComponent,resolve: {allfolders: function(FolderService) {return FolderService.list();}},}registry.register(foldersState);
property abstract
abstract?: boolean;
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.
property data
data?: any;
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 childdata
objects. Care should be taken if you are usinghasOwnProperty
on thedata
object. Properties from parent objects will return false forhasOwnProperty
.
property dynamic
dynamic?: boolean;
Marks all the state's parameters as
dynamic
.All parameters on the state will use this value for
dynamic
as a default. Individual parameters may override this default using [[ParamDeclaration.dynamic]] in the [[params]] block.Note: this value overrides the
dynamic
value on a custom parameter type ([[ParamTypeDefinition.dynamic]]).
property lazyLoad
lazyLoad?: ( transition: Transition, state: StateDeclaration) => Promise<LazyLoadResult>;
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 return 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) => import('./abcService')}The
abcService
file is imported and loaded (it is assumed that theabcService
file knows how to register itself as a service).#### Lifecycle
- The
lazyLoad
function is invoked if a transition is going to enter the state. - The function is invoked before the transition starts (using anonBefore
transition hook). - The function is only invoked once; while thelazyLoad
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. - When the promise resolves successfully, thelazyLoad
property is deleted from the state declaration. - If the promise resolves to a [[LazyLoadResult]] which has an array ofstates
, those states are registered. - The original transition is retried (this time without thelazyLoad
property present).- If the
lazyLoad
function fails, then the transition also fails. The failed transition (and thelazyLoad
function) could potentially be retried by the user.### Lazy loading state definitions (Future States)
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:
- A
name
which ends in.**
. A future state'sname
property acts as a wildcard [[Glob]]. It matches any state name that starts with thename
(including child states that are not yet loaded). - Aurl
prefix. A future state'surl
property acts as a wildcard. UI-Router matches all paths that begin with theurl
. It effectively appends.*
to the internal regular expression. When the prefix matches, the future state will begin loading. - AlazyLoad
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.### Additional resources
For in depth information on lazy loading and Future States, see the [Lazy Loading Guide](https://ui-router.github.io/guides/lazyload).
#### Example: states.js
// This child state is a lazy loaded future state// The `lazyLoad` function loads the final state definition{name: 'parent.**',url: '/parent',lazyLoad: () => import('./lazy.states.js')}#### Example: 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 statelet parentState = {// the name should match the future statename: '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 hooklet lazyLoadResults = {states: [ parentState, childState ]};export default lazyLoadResults;Parameter transition
the [[Transition]] that is activating the future state
Parameter state
the [[StateDeclaration]] that the
lazyLoad
function is declared on a Promise to load the states. Optionally, if the promise resolves to a [[LazyLoadResult]], the states will be registered with the [[StateRegistry]].
property name
name?: string;
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.
property onEnter
onEnter?: TransitionStateHookFn;
A Transition Hook called with the state is being entered. See: [[IHookRegistry.onEnter]]
#### Example:
.state({name: 'mystate',onEnter: function(trans, state) {console.log("Entering " + state.name);}});Note: The above
onEnter
on the state declaration is effectively sugar for:transitionService.onEnter({ entering: 'mystate' }, function(trans, state) {console.log("Entering " + state.name);});
property onExit
onExit?: TransitionStateHookFn;
A Transition Hook called with the state is being exited. See: [[IHookRegistry.onExit]]
#### Example:
.state({name: 'mystate',onExit: function(trans, state) {console.log("Leaving " + state.name);}});Note: The above
onRetain
on the state declaration is effectively sugar for:transitionService.onExit({ exiting: 'mystate' }, function(trans, state) {console.log("Leaving " + state.name);});
property onRetain
onRetain?: TransitionStateHookFn;
A [[TransitionStateHookFn]] called with the state is being retained/kept. See: [[IHookRegistry.onRetain]]
#### Example:
.state({name: 'mystate',onRetain: function(trans, state) {console.log(state.name + " is still active!");}});Note: The above
onRetain
on the state declaration is effectively sugar for:transitionService.onRetain({ retained: 'mystate' }, function(trans, state) {console.log(state.name + " is still active!");});
property params
params?: { [key: string]: ParamDeclaration | any;};
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.
#### Example:
params: {param1: {type: "int",array: true,value: []},param2: {value: "index"}}
property parent
parent?: string | StateDeclaration;
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 `ChildWhen using this property, the state's name should not have any dots in it.
#### Example:
var parentstate = {name: 'parentstate'}var childstate = {name: 'childstate',parent: 'parentstate'// or use a JS var which is the parent StateDeclaration, i.e.:// parent: parentstate}
property redirectTo
redirectTo?: | RedirectToResult | ((transition: Transition) => RedirectToResult) | ((transition: Transition) => Promise<RedirectToResult>);
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/orparams
property, the Transition is redirected to the namedstate
and/orparams
.- If the value is a [[TargetState]] the Transition is redirected to the
TargetState
- If the property is a function: - The function is called with the current [[Transition]] - The return value is processed using the previously mentioned rules. - If the return value is a promise, the promise is waited for, then the resolved async value is processed using the same rules.
Note:
redirectTo
is processed as anonStart
hook, beforeLAZY
resolves. If your redirect function relies on resolve data, get the [[Transition.injector]] and get a promise for the resolve data using [[UIInjector.getAsync]].#### Example:
// 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 loadlet resolvePromise = trans.injector().getAsync('SomeResolve')return resolvePromise.then(resolveData => resolveData === 'login' ? 'login' : null);}})
property reloadOnSearch
reloadOnSearch?: boolean;
Marks all query parameters as [[ParamDeclaration.dynamic]]
Deprecated
use either [[dynamic]] or [[ParamDeclaration.dynamic]]
property resolve
resolve?: | ResolveTypes[] | { [key: string]: IInjectable; };
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 may be used in views, transition hooks or other resolves that belong to this state. The data may also be used in any views or resolves that belong to nested states.### As an array
Each array element should be a [[ResolvableLiteral]] object.
#### Example: The
user
resolve injects the currentTransition
and theUserService
(using its token, which is a string). The [[ResolvableLiteral.resolvePolicy]] sets how the resolve is processed. Theuser
data, fetched asynchronously, can then be used in a view.var state = {name: 'user',url: '/user/:userIdresolve: [{token: 'user',policy: { when: 'EAGER' },deps: ['UserService', Transition],resolveFn: (userSvc, trans) => userSvc.fetchUser(trans.params().userId) },}]}Note: an Angular 2 style [
useFactory
provider literal](https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#provide) may also be used. See [[ProviderLike]]. #### Example:resolve: [{ provide: 'token', useFactory: (http) => http.get('/'), deps: [ Http ] },]### As an object
The
resolve
property may be an object where: - Each key (string) is the name of the dependency. - Each value (function) is an injectable function which returns the dependency, or a promise for the dependency.This style is based on AngularJS injectable functions, but can be used with any UI-Router implementation. If your code will be minified, the function should be ["annotated" in the AngularJS manner](https://docs.angularjs.org/guide/di#dependency-annotation).
#### AngularJS Example:
resolve: {// If you inject `myStateDependency` into a controller, you'll get "abc"myStateDependency: function() {return "abc";},// Dependencies are annotated in "Inline Array Annotation"myAsyncData: ['$http', '$transition$' function($http, $transition$) {// Return a promise (async) for the datareturn $http.get("/foos/" + $transition$.params().foo);}]}Note: You cannot specify a policy for each Resolvable, nor can you use non-string tokens when using the object style
resolve:
block.### Lifecycle
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* during the
Transition
have their resolves fetched. States that are "retained" do not have their resolves re-fetched.If you are currently in a parent state
parent
and are transitioning to a child stateparent.child
, the previously resolved data for stateparent
can be injected intoparent.child
without delay.Any resolved data for
parent.child
is retained untilparent.child
is exited, e.g., by transitioning back to theparent
state.Because of this scoping and lifecycle, resolves are a great place to fetch your application's primary data.
### Injecting resolves into other things
During a transition, Resolve data can be injected into:
- Views (the components which fill a
ui-view
tag) - Transition Hooks - Other resolves (a resolve may depend on asynchronous data from a different resolve)### Injecting other things into resolves
Resolve functions usually have dependencies on some other API(s). The dependencies are usually declared and injected into the resolve function. A common pattern is to inject a custom service such as
UserService
. The resolve then delegates to a service method, such asUserService.list()
;#### Special injectable tokens
-
UIRouter
: The [[UIRouter]] instance which has references to all the UI-Router services. -Transition
: The current [[Transition]] object; information and API about the current transition, such as "to" and "from" State Parameters and transition options. -'$transition$'
: A string alias for theTransition
injectable -'$state$'
: ForonEnter
/onExit
/onRetain
, the state being entered/exited/retained. - Other resolve tokens: A resolve can depend on another resolve, either from the same state, or from any parent state.#### Example:
// Injecting a resolve into another resolveresolve: [// 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] }}
property resolvePolicy
resolvePolicy?: ResolvePolicy;
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", CustomAsyncPolicySee [[ResolvePolicy]] for more details.
property url
url?: string;
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.
url: "/home"// Define a parameter named 'userid'url: "/users/:userid"// param 'bookid' has a custom regexpurl: "/books/{bookid:[a-zA-Z_-]}"// param 'categoryid' is of type 'int'url: "/books/{categoryid:int}"// two parameters for this stateurl: "/books/{publishername:string}/{categoryid:int}"// Query parametersurl: "/messages?before&after"// Query parameters of type 'date'url: "/messages?{before:date}&{after:date}"// Path and query parametersurl: "/messages/:mailboxid?{before:date}&{after:date}"
property views
views?: { [key: string]: _ViewDeclaration;};
Named views
An optional object which defines multiple views, or explicitly targets specific named ui-views.
- What is a view config - What is a ui-view - Shorthand controller/template - Incompatible with ^
Examples:
Targets three named ui-views in the parent state's template
#### Example:
views: {header: {controller: "headerCtrl",templateUrl: "header.html"}, body: {controller: "bodyCtrl",templateUrl: "body.html"}, footer: {controller: "footCtrl",templateUrl: "footer.html"}}Example 1
// Targets named ui-view="header" from ancestor state 'top''s template, and// named `ui-view="body" from parent state's template.views: {'header@top': {controller: "msgHeaderCtrl",templateUrl: "msgHeader.html"}, 'body': {controller: "messagesCtrl",templateUrl: "messages.html"}}
interface StateRule
interface StateRule extends MatcherUrlRule {}
interface TargetStateDef
interface TargetStateDef {}
interface TransitionCreateHookFn
interface TransitionCreateHookFn {}
The signature for Transition onCreate Hooks.
Transition onCreate Hooks are callbacks that allow customization or preprocessing of a Transition before it is returned from [[TransitionService.create]]
Parameter transition
the [[Transition]] that was just created a [[Transition]] which will then be returned from [[TransitionService.create]]
call signature
(transition: Transition): void;
interface TransitionHookFn
interface TransitionHookFn {}
The signature for Transition Hooks.
Transition hooks are callback functions that hook into the lifecycle of transitions. As a transition runs, it reaches certain lifecycle events. As each event occurs, the hooks which are registered for the event are called (in priority order).
A transition hook may alter a Transition by returning a [[HookResult]].
#### See:
- [[IHookRegistry.onBefore]] - [[IHookRegistry.onStart]] - [[IHookRegistry.onFinish]] - [[IHookRegistry.onSuccess]] - [[IHookRegistry.onError]]
Parameter transition
the current [[Transition]]
Parameter injector
(for ng1 or ng2 only) the injector service
Returns
a [[HookResult]] which may alter the transition
call signature
(transition: Transition): HookResult;
interface TransitionHookOptions
interface TransitionHookOptions {}
interface TransitionOptions
interface TransitionOptions {}
The TransitionOptions object can be used to change the behavior of a transition.
It is passed as the third argument to [[StateService.go]], [[StateService.transitionTo]]. It can also be used with a
uiSref
.
property custom
custom?: any;
You can define your own Transition Options inside this property and use them, e.g., from a Transition Hook
property inherit
inherit?: boolean;
This option sets whether or not the transition's parameter values should be inherited from the current parameter values.
- If
true
, it will inherit parameter values from the current parameter values. - Iffalse
, only the parameters which are provided totransitionTo
will be used.true
property location
location?: boolean | 'replace';
This option changes how the Transition interacts with the browser's location bar (URL).
- If
true
, it will update the url in the location bar. - Iffalse
, it will not update the url in the location bar. - If it is the string"replace"
, it will update the url and also replace the last history record.true
property notify
notify?: boolean;
Deprecated
property relative
relative?: string | StateDeclaration | StateObject;
When transitioning to relative path (e.g '
^
'), this option defines which state to be relative from.$state.current
property reload
reload?: boolean | string | StateDeclaration | StateObject;
This option may be used to force states which are currently active to reload.
During a normal transition, a state is "retained" if: - It was previously active - The state's parameter values have not changed - All the parent states' parameter values have not changed
Forcing a reload of a state will cause it to be exited and entered, which will: - Refetch that state's resolve data - Exit the state (onExit hook) - Re-enter the state (onEnter hook) - Re-render the views (controllers and templates)
- When
true
, the destination state (and all parent states) will be reloaded. - When it is a string and is the name of a state, or when it is a State object, that state and any children states will be reloaded.false
property supercede
supercede?: boolean;
This option may be used to cancel the active transition (if one is active) in favour of the this one. This is the default behaviour or ui-router.
- When
true
, the active transition will be canceled and new transition will begin. - whenfalse
, the transition will be canceled if a transition is already running. This can be useful in cases where you only want to navigate to a different state if you are not already navigating somewhere.true
interface TransitionPromise
interface TransitionPromise extends Promise<StateObject> {}
property transition
transition: Transition;
interface TransitionServicePluginAPI
interface TransitionServicePluginAPI {}
Plugin API for Transition Service
method getHooks
getHooks: (hookName: string) => RegisteredHook[];
Returns the hooks registered for the given hook name
interface TransitionStateHookFn
interface TransitionStateHookFn {}
The signature for Transition State Hooks.
A function which hooks into a lifecycle event for a specific state.
Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition. As a transition runs, it may exit some states, retain (keep) states, and enter states. As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).
#### See:
- [[IHookRegistry.onExit]] - [[IHookRegistry.onRetain]] - [[IHookRegistry.onEnter]]
Parameter transition
the current [[Transition]]
Parameter state
the [[StateObject]] that the hook is bound to
Parameter injector
(for ng1 or ng2 only) the injector service
Returns
a [[HookResult]] which may alter the transition
call signature
(transition: Transition, state: StateDeclaration): HookResult;
interface TreeChanges
interface TreeChanges {}
TreeChanges encapsulates the various Paths that are involved in a Transition.
Get a TreeChanges object using [[Transition.treeChanges]]
A UI-Router Transition is from one Path in a State Tree to another Path. For a given Transition, this object stores the "to" and "from" paths, as well as subsets of those: the "retained", "exiting" and "entering" paths.
Each path in TreeChanges is an array of [[PathNode]] objects. Each PathNode in the array corresponds to a portion of a nested state.
For example, if you had a nested state named
foo.bar.baz
, it would have three portions,foo, bar, baz
. If you transitioned **to**foo.bar.baz
and inspected the [[TreeChanges.to]] Path, you would find a node in the array for each portion:foo
,bar
, andbaz
.---
show visual state tree
property entering
entering: PathNode[];
The path of nodes that the transition is entering.
After the Transition is successful, these nodes will be active. Because they are entering, they have their resolves fetched,
onEnter
hooks run, and their views (component(s) or controller(s)+template(s)) refreshed.Note that a state that is reloaded (due to parameter values changing, or
reload: true
) may be in both theexiting
andentering
paths.
property exiting
exiting: PathNode[];
The path of previously active nodes that the transition is exiting.
After the Transition is successful, these nodes are no longer active.
Note that a state that is being reloaded (due to parameter values changing, or
reload: true
) may be in both theexiting
andentering
paths.
property from
from: PathNode[];
The path of nodes in the state tree that the transition is coming *from*
property retained
retained: PathNode[];
The path of active nodes that the transition is retaining.
These nodes are neither exited, nor entered. Before and after the transition is successful, these nodes are active.
property retainedWithToParams
retainedWithToParams: PathNode[];
The path of active nodes that the transition is retaining with updated "to params" applied.
These nodes are neither exited, nor entered. Before and after the transition is successful, these nodes are active.
This is a shallow copy of [[retained]], but with new (dynamic) parameter values from [[to]] applied.
property to
to: PathNode[];
The path of nodes in the state tree that the transition is going *to*
index signature
[key: string]: PathNode[] | undefined;
interface TypedMap
interface TypedMap<T> {}
index signature
[key: string]: T;
interface UIInjector
interface UIInjector {}
An interface for getting values from dependency injection.
This is primarily used to get resolve values for a given token. An instance of the
UIInjector
can be retrieved from the current transition using [[Transition.injector]].---
If no resolve is found for a token, then it will delegate to the native injector. The native injector may be Angular 1
$injector
, Angular 2Injector
, or a simple polyfill.In Angular 2, the native injector might be the root Injector, or it might be a lazy loaded
NgModule
injector scoped to a lazy load state tree.
method get
get: { (token: any): any; <T>(token: any): T };
Gets a value from the injector.
For a given token, returns the value from the injector that matches the token. If the token is for a resolve that has not yet been fetched, this throws an error.
#### Example:
var myResolve = injector.get('myResolve');#### ng1 Example:
// Fetch StateServiceinjector.get('$state').go('home');#### ng2 Example:
import {StateService} from "ui-router-ng2";// Fetch StateServiceinjector.get(StateService).go('home');#### Typescript Example:
var stringArray = injector.get<string[]>('myStringArray');###
NOWAIT
policyWhen using [[ResolvePolicy.async]] ===
NOWAIT
, the value returned fromget()
is a promise for the result. The promise is not automatically unwrapped.Parameter token
the key for the value to get. May be a string, a class, or any arbitrary object. the Dependency Injection value that matches the token
Gets a value as type
T
(generics parameter)
method getAsync
getAsync: { (token: any): Promise<any>; <T>(token: any): Promise<T> };
Asynchronously gets a value from the injector
For a given token, returns a promise for the value from the injector that matches the token. If the token is for a resolve that has not yet been fetched, this triggers the resolve to load.
#### Example:
return injector.getAsync('myResolve').then(value => {if (value === 'declined') return false;});Parameter token
the key for the value to get. May be a string or arbitrary object. a Promise for the Dependency Injection value that matches the token
Asynchronously gets a value as type
T
(generics parameter)
method getNative
getNative: { (token: any): any; <T>(token: any): T };
Gets a value from the native injector
Returns a value from the native injector, bypassing anything in the [[ResolveContext]].
Example:
let someThing = injector.getNative(SomeToken);Parameter token
the key for the value to get. May be a string or arbitrary object. the Dependency Injection value that matches the token
interface UIRouterPlugin
interface UIRouterPlugin extends Disposable {}
property name
name: string;
interface UrlConfigApi
interface UrlConfigApi extends LocationConfig, UrlMatcherConfig {}
Deprecated
use [[UrlConfig]]
interface UrlMatcherCompileConfig
interface UrlMatcherCompileConfig {}
property caseInsensitive
caseInsensitive?: boolean;
property decodeParams
decodeParams?: boolean;
property state
state?: StateDeclaration;
property strict
strict?: boolean;
interface UrlMatcherConfig
interface UrlMatcherConfig {}
Deprecated
use [[UrlConfig]]
property caseInsensitive
caseInsensitive: UrlConfig['caseInsensitive'];
See: [[UrlConfig.caseInsensitive]]
property defaultSquashPolicy
defaultSquashPolicy: UrlConfig['defaultSquashPolicy'];
See: [[UrlConfig.defaultSquashPolicy]]
property strictMode
strictMode: UrlConfig['strictMode'];
See: [[UrlConfig.strictMode]]
property type
type: UrlConfig['type'];
See: [[UrlConfig.type]]
interface UrlParts
interface UrlParts {}
An object containing the three parts of a URL
interface UrlRule
interface UrlRule {}
The interface for a URL Rule
If you are creating a rule for use with [[UrlRules.rule]], it should implement this interface.
property $id
$id: number;
The rule's ID.
IDs are auto-assigned when the rule is registered, in increasing order.
property handler
handler: UrlRuleHandlerFn;
This function is called if the rule matched, and was selected as the "best match". This function handles the rule match event.
See [[UrlRuleHandlerFn]] for details
property match
match: UrlRuleMatchFn;
This function should match the url and return the match details
See [[UrlRuleMatchFn]] for details
property priority
priority: number;
The rule's priority (defaults to 0).
This can be used to explicitly modify the rule's priority. Higher numbers are higher priority.
property type
type: UrlRuleType;
The type of the rule
method matchPriority
matchPriority: (match: any) => number;
The priority of a given match.
Sometimes more than one UrlRule might have matched. This method is used to choose the best match.
If multiple rules matched, each rule's
matchPriority
is called with the value from [[match]]. The rule with the highestmatchPriority
has its [[handler]] called.
interface UrlRuleHandlerFn
interface UrlRuleHandlerFn {}
Handler invoked when a rule is matched
The matched value from the rule's [[UrlRuleMatchFn]] is passed as the first argument The handler should return a string (to redirect), a [[TargetState]]/[[TargetStateDef]], or void
If the handler returns a string, the url is replaced with the string. If the handler returns a [[TargetState]], the target state is activated.
call signature
(matchValue?: any, url?: UrlParts, router?: UIRouter): | string | TargetState | TargetStateDef | void;
interface UrlRuleMatchFn
interface UrlRuleMatchFn {}
A function that matches the URL for a [[UrlRule]]
Implementations should match against the provided [[UrlParts]] and return the matched value (truthy) if the rule matches. If this rule is selected, the matched value is passed to the [[UrlRuleHandlerFn]].
the matched value, either truthy or falsey
call signature
(url?: UrlParts, router?: UIRouter): any;
interface UrlRulesApi
interface UrlRulesApi {}
Deprecated
use [[UrlRules]]
property initial
initial: UrlRules['initial'];
See: [[UrlRules.initial]]
property otherwise
otherwise: UrlRules['otherwise'];
See: [[UrlRules.otherwise]]
property removeRule
removeRule: UrlRules['removeRule'];
See: [[UrlRules.removeRule]]
property rule
rule: UrlRules['rule'];
See: [[UrlRules.rule]]
property rules
rules: UrlRules['rules'];
See: [[UrlRules.rules]]
property sort
sort: UrlRules['sort'];
See: [[UrlRules.sort]]
property when
when: UrlRules['when'];
See: [[UrlRules.when]]
interface UrlSyncApi
interface UrlSyncApi {}
Deprecated
use [[UrlService]]
property deferIntercept
deferIntercept: UrlService['deferIntercept'];
See: [[UrlService.deferIntercept]]
property listen
listen: UrlService['listen'];
See: [[UrlService.listen]]
property sync
sync: UrlService['sync'];
See: [[UrlService.sync]]
interface ViewConfig
interface ViewConfig {}
This interface represents a [[_ViewDeclaration]] that is bound to a [[PathNode]].
A
ViewConfig
is the runtime definition of a single view.During a transition,
ViewConfig
s are created for each [[_ViewDeclaration]] defined on each "entering" [[StateObject]]. Then, the [[ViewService]] finds any matchingui-view
(s) in the DOM, and supplies the ui-view with theViewConfig
. Theui-view
then loads itself using the information found in theViewConfig
.A
ViewConfig
if matched with aui-view
by finding allui-view
s which were created in the context named by theuiViewContextAnchor
, and finding theui-view
or childui-view
that matches theuiViewName
address.
property $id
$id: number;
property loaded
loaded: boolean;
property path
path: PathNode[];
The node the ViewConfig is bound to
property viewDecl
viewDecl: _ViewDeclaration;
The normalized view declaration from [[State.views]]
method load
load: () => Promise<ViewConfig>;
Fetches templates, runs dynamic (controller|template)Provider code, lazy loads Components, etc
interface ViewContext
interface ViewContext {}
The context ref can be anything that has a
name
and aparent
reference to another IContextRef
interface ViewServicePluginAPI
interface ViewServicePluginAPI {}
interface ViewSyncListener
interface ViewSyncListener {}
call signature
(viewTuples: ViewTuple[]): void;
interface ViewTuple
interface ViewTuple {}
property uiView
uiView: ActiveUIView;
property viewConfig
viewConfig: ViewConfig;
Enums
enum Category
enum Category { RESOLVE = 0, TRANSITION = 1, HOOK = 2, UIVIEW = 3, VIEWCONFIG = 4,}
Trace categories Enum
Enable or disable a category using [[Trace.enable]] or [[Trace.disable]]
trace.enable(Category.TRANSITION)
These can also be provided using a matching string, or position ordinal
trace.enable("TRANSITION")
trace.enable(1)
member HOOK
HOOK = 2
member RESOLVE
RESOLVE = 0
member TRANSITION
TRANSITION = 1
member UIVIEW
UIVIEW = 3
member VIEWCONFIG
VIEWCONFIG = 4
enum DefType
enum DefType { PATH = 0, SEARCH = 1, CONFIG = 2,}
enum RejectType
enum RejectType { SUPERSEDED = 2, ABORTED = 3, INVALID = 4, IGNORED = 5, ERROR = 6,}
An enum for Transition Rejection reasons
member ABORTED
ABORTED = 3
The transition was aborted
The transition was aborted by a hook which returned
false
member ERROR
ERROR = 6
The transition errored.
This generally means a hook threw an error or returned a rejected promise
member IGNORED
IGNORED = 5
The transition was ignored
The transition was ignored because it would have no effect.
Either:
- The transition is targeting the current state and parameter values - The transition is targeting the same state and parameter values as the currently running transition.
member INVALID
INVALID = 4
The transition was invalid
The transition was never started because it was invalid
member SUPERSEDED
SUPERSEDED = 2
A new transition superseded this one.
While this transition was running, a new transition started. This transition is cancelled because it was superseded by new transition.
enum TransitionHookPhase
enum TransitionHookPhase { CREATE = 0, BEFORE = 1, RUN = 2, SUCCESS = 3, ERROR = 4,}
enum TransitionHookScope
enum TransitionHookScope { TRANSITION = 0, STATE = 1,}
member STATE
STATE = 1
member TRANSITION
TRANSITION = 0
Type Aliases
type BuilderFunction
type BuilderFunction = (state: StateObject, parent?: BuilderFunction) => any;
A function that builds the final value for a specific field on a [[StateObject]].
A series of builder functions for a given field are chained together. The final value returned from the chain of builders is applied to the built [[StateObject]]. Builder functions should call the [[parent]] function either first or last depending on the desired composition behavior.
Parameter state
the _partially built_ [[StateObject]]. The [[StateDeclaration]] can be inspected via [[StateObject.self]]
Parameter parent
the previous builder function in the series.
type ErrorHandler
type ErrorHandler = (error: any) => Promise<any>;
type GetErrorHandler
type GetErrorHandler = (hook: TransitionHook) => ErrorHandler;
type GetResultHandler
type GetResultHandler = (hook: TransitionHook) => ResultHandler;
type HookFn
type HookFn = TransitionHookFn | TransitionStateHookFn | TransitionCreateHookFn;
type HookMatchCriterion
type HookMatchCriterion = string | IStateMatch | boolean;
Hook Criterion used to match a transition.
A [[Glob]] string that matches the name of a state.
Or, a function with the signature
function(state, transition) { return matches; }
which should return a boolean to indicate if a state matches.Or,
true
to always match
type HookResult
type HookResult = | boolean | TargetState | void | Promise<boolean | TargetState | void>;
The return value of a [[TransitionHookFn]] or [[TransitionStateHookFn]]
When returned from a [[TransitionHookFn]] or [[TransitionStateHookFn]], these values alter the running [[Transition]]:
-
false
: the transition will be cancelled. - [[TargetState]]: the transition will be redirected to the new target state (see: [[StateService.target]]) -Promise
: the transition will wait for the promise to resolve or reject - If the promise is rejected (or resolves tofalse
), the transition will be cancelled - If the promise resolves to a [[TargetState]], the transition will be redirected - If the promise resolves to anything else, the transition will resume - Anything else: the transition will resume
type IHookRegistration
type IHookRegistration = ( matchCriteria: HookMatchCriteria, callback: HookFn, options?: HookRegOptions) => Function;
type IInjectable
type IInjectable = Function | any[];
An ng1-style injectable
This could be a (non-minified) function such as:
function injectableFunction(SomeDependency) {}or an explicitly annotated function (minify safe)
injectableFunction.$inject = [ 'SomeDependency' ];function injectableFunction(SomeDependency) {}or an array style annotated function (minify safe)
['SomeDependency', function injectableFunction(SomeDependency) {}];
type IStateMatch
type IStateMatch = PredicateBinary<StateObject, Transition>;
A predicate type which tests if a [[StateObject]] and [[Transition]] passes some test. Returns a boolean.
type Mapper
type Mapper<X, T> = (x: X, key?: string | number) => T;
type OnInvalidCallback
type OnInvalidCallback = ( toState?: TargetState, fromState?: TargetState, injector?: UIInjector) => HookResult;
type PolicyAsync
type PolicyAsync = 'WAIT' | 'NOWAIT' | CustomAsyncPolicy;
type PolicyWhen
type PolicyWhen = 'LAZY' | 'EAGER';
type Predicate
type Predicate<X> = (x?: X) => boolean;
type PredicateBinary
type PredicateBinary<X, Y> = (x?: X, y?: Y) => boolean;
type RedirectToResult
type RedirectToResult = | string | TargetState | { state?: string; params?: RawParams; } | void;
The return value of a [[redirectTo]] function
- string: a state name - TargetState: a target state, parameters, and options - object: an object with a state name and parameters
type ResolveTypes
type ResolveTypes = Resolvable | ResolvableLiteral | ProviderLike;
type ResultHandler
type ResultHandler = (result: HookResult) => Promise<HookResult>;
type StateOrName
type StateOrName = string | StateDeclaration | StateObject;
type StateRegistryListener
type StateRegistryListener = ( event: 'registered' | 'deregistered', states: StateDeclaration[]) => void;
The signature for the callback function provided to [[StateRegistry.onStatesChanged]].
This callback receives two parameters:
Parameter event
a string; either "registered" or "deregistered"
Parameter states
the list of [[StateDeclaration]]s that were registered (or deregistered).
type ViewConfigFactory
type ViewConfigFactory = ( path: PathNode[], decl: _ViewDeclaration) => ViewConfig | ViewConfig[];
Package Files (59)
- lib/common/common.d.ts
- lib/common/coreservices.d.ts
- lib/common/glob.d.ts
- lib/common/hof.d.ts
- lib/common/predicates.d.ts
- lib/common/queue.d.ts
- lib/common/strings.d.ts
- lib/common/trace.d.ts
- lib/globals.d.ts
- lib/index.d.ts
- lib/interface.d.ts
- lib/params/interface.d.ts
- lib/params/param.d.ts
- lib/params/paramType.d.ts
- lib/params/paramTypes.d.ts
- lib/params/stateParams.d.ts
- lib/path/pathNode.d.ts
- lib/path/pathUtils.d.ts
- lib/resolve/interface.d.ts
- lib/resolve/resolvable.d.ts
- lib/resolve/resolveContext.d.ts
- lib/router.d.ts
- lib/state/interface.d.ts
- lib/state/stateBuilder.d.ts
- lib/state/stateMatcher.d.ts
- lib/state/stateObject.d.ts
- lib/state/stateQueueManager.d.ts
- lib/state/stateRegistry.d.ts
- lib/state/stateService.d.ts
- lib/state/targetState.d.ts
- lib/transition/hookBuilder.d.ts
- lib/transition/hookRegistry.d.ts
- lib/transition/interface.d.ts
- lib/transition/rejectFactory.d.ts
- lib/transition/transition.d.ts
- lib/transition/transitionEventType.d.ts
- lib/transition/transitionHook.d.ts
- lib/transition/transitionService.d.ts
- lib/url/interface.d.ts
- lib/url/urlConfig.d.ts
- lib/url/urlMatcher.d.ts
- lib/url/urlMatcherFactory.d.ts
- lib/url/urlRouter.d.ts
- lib/url/urlRule.d.ts
- lib/url/urlRules.d.ts
- lib/url/urlService.d.ts
- lib/vanilla/baseLocationService.d.ts
- lib/vanilla/browserLocationConfig.d.ts
- lib/vanilla/hashLocationService.d.ts
- lib/vanilla/injector.d.ts
- lib/vanilla/interface.d.ts
- lib/vanilla/memoryLocationConfig.d.ts
- lib/vanilla/memoryLocationService.d.ts
- lib/vanilla/plugins.d.ts
- lib/vanilla/pushStateLocationService.d.ts
- lib/vanilla/q.d.ts
- lib/vanilla/utils.d.ts
- lib/view/interface.d.ts
- lib/view/view.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (28)
- @types/jasmine
- @types/jquery
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- @uirouter/publish-scripts
- bufferutil
- dts-downlevel
- eslint
- fork-ts-checker-webpack-plugin
- husky
- jasmine-core
- karma
- karma-chrome-launcher
- karma-firefox-launcher
- karma-jasmine
- karma-script-launcher
- karma-sourcemap-loader
- karma-webpack
- prettier
- pretty-quick
- rollup
- rollup-plugin-node-resolve
- rollup-plugin-sourcemaps
- rollup-plugin-uglify
- ts-loader
- typescript
- utf-8-validate
- webpack
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@uirouter/core
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@uirouter/core)
- HTML<a href="https://www.jsdocs.io/package/@uirouter/core"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 13470 ms. - Missing or incorrect documentation? Open an issue for this package.