# Class StateService

Provides services related to ui-router states.

This API is located at `router.stateService` ([[UIRouter.stateService]])

- Defined in router/state/state-service.js:30

#####
Index

### Constructors

constructor

### Properties

$get
_defaultErrorHandler
globals
invalidCallbacks
stateRegistry
transitionService
urlService
$inject

### Accessors

$current
current
params

### Methods

_handleInvalidTargetState
decorator
defaultErrorHandler
get
getCurrentPath
go
href
includes
is
lazyLoad
onInvalid
reload
state
target
transitionTo

##
Constructors

### constructor

- new StateService(globals, transitionService): StateService

- #### Parameters

  - globals: any
  - transitionService: any

  #### Returns StateService

  - Defined in router/state/state-service.js:59

##
Properties

### $get

$get: (() => StateService)[] = ...

- Defined in router/state/state-service.js:91

### _defaultErrorHandler

_defaultErrorHandler: (($error$: any) => never)

- Defined in router/state/state-service.js:66
- Defined in router/state/state-service.js:668

### globals

globals: any

- Defined in router/state/state-service.js:62

### invalidCallbacks

invalidCallbacks: any[]

- Defined in router/state/state-service.js:64

### stateRegistry

stateRegistry: any

- Defined in router/state/state-service.js:60

### transitionService

transitionService: any

- Defined in router/state/state-service.js:63

### urlService

urlService: any

- Defined in router/state/state-service.js:61

### `Static`$inject

$inject: string[] = ...

- Defined in router/state/state-service.js:56

##
Accessors

### $current

- get $current(): any

- The current [[StateObject]] (an internal API)

  #### Returns any

  #### Deprecated

  This is a passthrough through to [[UIRouterGlobals.$current]]

  - Defined in router/state/state-service.js:52

### current

- get current(): any

- The current [[StateDeclaration]]

  #### Returns any

  #### Deprecated

  This is a passthrough through to [[UIRouterGlobals.current]]

  - Defined in router/state/state-service.js:44

### params

- get params(): any

- The latest successful state parameters

  #### Returns any

  #### Deprecated

  This is a passthrough through to [[UIRouterGlobals.params]]

  - Defined in router/state/state-service.js:36

##
Methods

### _handleInvalidTargetState

- _handleInvalidTargetState(fromPath, toState): any
- `Internal`

  Handler for when [[transitionTo]] is called with an invalid state.

  Invokes the [[onInvalid]] callbacks, in natural order. Each callback's return value is checked in sequence until one of them returns an instance of TargetState. The results of the callbacks are wrapped in $q.resolve(), so the callbacks may return promises.

  If a callback returns an TargetState, then it is used as arguments to $state.transitionTo() and the result returned.

  #### Parameters

  - fromPath: any
  - toState: any

  #### Returns any

  - Defined in router/state/state-service.js:217

### decorator

- decorator(name, func): any

- Decorates states when they are registered

  Allows you to extend (carefully) or override (at your own peril) the `stateBuilder` object used internally by [[StateRegistry]]. This can be used to add custom functionality to ui-router, for example inferring templateUrl based on the state name.

  When passing only a name, it returns the current (original or decorated) builder function that matches `name`.

  The builder functions that can be decorated are listed below. Though not all necessarily have a good use case for decoration, that is up to you to decide.

  In addition, users can attach custom decorators, which will generate new properties within the state's internal definition. There is currently no clear use-case for this beyond accessing internal states (i.e. $state.$current), however, expect this to become increasingly relevant as we introduce additional meta-programming features.

  Warning: Decorators should not be interdependent because the order of execution of the builder functions in non-deterministic. Builder functions should only be dependent on the state definition object and super function.

  Existing builder functions and current return values:

  - parent `{object}` - returns the parent state object.
  - data `{object}` - returns state data, including any inherited data that is not overridden by own values (if any).
  - url `{object}` - returns a ui.router.util.type:UrlMatcher UrlMatcher or `null`.
  - navigable `{object}` - returns closest ancestor state that has a URL (aka is navigable).
  - params `{object}` - returns an array of state params that are ensured to be a super-set of parent's params.
  - views `{object}` - returns a views object where each key is an absolute view name (i.e. "viewName@stateName") and each value is the config object (template, controller) for the view. Even when you don't use the views object explicitly on a state config, one is still created for you internally. So by decorating this builder function you have access to decorating template and controller properties.
  - ownParams `{object}` - returns an array of params that belong to the state, not including any params defined by ancestor states.
  - path `{string}` - returns the full path from the root down to this state. Needed for state activation.
  - includes `{object}` - returns an object that includes every state that would pass a `$state.includes()` test.

  #### Example:

  Override the internal 'views' builder with a function that takes the state definition, and a reference to the internal function being overridden:

      $stateProvider.decorator('views', function (state, parent) {
        let result = {},
            views = parent(state);

        angular.forEach(views, function (config, name) {
          let autoName = (state.name + '.' + name).replace('.', '/');
          config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
          result[name] = config;
        });
        return result;
      });

      $stateProvider.state('home', {
        views: {
          'contact.list': { controller: 'ListController' },
          'contact.item': { controller: 'ItemController' }
        }
      });

      // Auto-populates list and item views with /partials/home/contact/list.html,
      // and /partials/home/contact/item.html, respectively.
      $state.go('home');

  #### Parameters

  - name: string

    The name of the builder function to decorate.

  - func: any

    A function that is responsible for decorating the original builder function. The function receives two parameters:

    - `{object}` - state - The state config object.
    - `{object}` - super - The original builder function.

  #### Returns any

  $stateProvider - $stateProvider instance

  - Defined in router/state/state-service.js:186

### defaultErrorHandler

- defaultErrorHandler(handler): any

- 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
      });

  #### Parameters

  - handler: any

    a global error handler function

  #### Returns any

  the current global error handler

  - Defined in router/state/state-service.js:667

### get

- get(stateOrName, base, ...args): any

- #### Parameters

  - stateOrName: any
  - base: any
  - `Rest`...args: any

  #### Returns any

  - Defined in router/state/state-service.js:671

### getCurrentPath

- getCurrentPath(): any

- #### Returns any

  - Defined in router/state/state-service.js:409

### go

- go(to, params, options): Promise<any>

- 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 relative `to` argument (because of `relative: 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 of `inherit: true`).

  #### Example:

      let app = angular.module('app', ['ui.router']);

      app.controller('ctrl', function ($scope, $state) {
        $scope.changeState = function () {
          $state.go('contact.detail');
        };
      });

  #### Parameters

  - to: any

    Absolute state name, state object, or relative state path (relative to current state).

    Some examples:

    - `$state.go('contact.detail')` - will go to the `contact.detail` state
    - `$state.go('^')` - will go to the parent state
    - `$state.go('^.sibling')` - if current state is `home.child`, will go to the `home.sibling` state
    - `$state.go('.child.grandchild')` - if current state is home, will go to the `home.child.grandchild` state
  - params: any

    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.

  - options: any

    Transition options

  #### Returns Promise<any>

  A promise representing the state of the new transition.

  - Defined in router/state/state-service.js:381

### href

- href(stateOrName, params, options): 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");

  #### Parameters

  - stateOrName: any

    The state name or state object you'd like to generate a url from.

  - params: any

    An object of parameter values to fill the state's required parameters.

  - options: any

    Options object. The options are:

  #### Returns string

  compiled state url

  - Defined in router/state/state-service.js:619

### includes

- includes(stateOrName, params, options): 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 false

  #### Parameters

  - stateOrName: any

    A partial name, relative name, glob pattern, or state object to be searched for within the current state name.

  - params: any

    A param object, e.g. `{sectionId: section.id}`, that you'd like to test against the current active state.

  - options: any

    An options object. The options are:

    - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will test relative to `options.relative` state (or name).

  #### Returns boolean

  Returns true if it does include the state

  - Defined in router/state/state-service.js:581

### is

- is(stateOrName, params, options): 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>

  #### Parameters

  - stateOrName: any

    The state name (absolute or relative) or state object you'd like to check.

  - params: any

    A param object, e.g. `{sectionId: section.id}`, that you'd like to test against the current active state.

  - options: any

    An options object. The options are:

    - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will test relative to `options.relative` state (or name).

  #### Returns boolean

  Returns true if it is the state.

  - Defined in router/state/state-service.js:527

### lazyLoad

- lazyLoad(stateOrName, transition): any

- Lazy loads a state

  Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.

  #### Parameters

  - stateOrName: any

    the state that should be lazy loaded

  - transition: any

    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 any

  a promise to lazy load

  - Defined in router/state/state-service.js:688

### onInvalid

- onInvalid(callback): any

- 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'));
        }
      });

  #### Parameters

  - callback: Function

    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 any

  a function which deregisters the callback

  - Defined in router/state/state-service.js:284

### reload

- reload(reloadState): any

- 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
      });

  #### Parameters

  - reloadState: any

    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 any

  A promise representing the state of the new transition. See [[StateService.go]]

  - Defined in router/state/state-service.js:334

### state

- state(definition): StateService

- #### Parameters

  - definition: any

  #### Returns StateService

  - Defined in router/state/state-service.js:194

### target

- target(identifier, params, options?): 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.

  #### Parameters

  - identifier: any
  - params: any
  - options: {} = {}

  #### Returns TargetState

  - Defined in router/state/state-service.js:393

### transitionTo

- transitionTo(to, toParams?, options?): any

- 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');
        };
      });

  #### Parameters

  - to: any

    State name or state object.

  - toParams: {} = {}

    A map of the parameters that will be sent to the state, will populate $stateParams.

  - options: {} = {}

    Transition options

  #### Returns any

  A promise representing the state of the new transition. See [[go]]

  - Defined in router/state/state-service.js:438