Skip to content
Chris Boden edited this page Sep 5, 2013 · 113 revisions

ANYTHING MISSING? Please add it to this list to be documented.


Module Configuration

Configure your states in your module's config method.

Be sure to include ui.router as a module dependency.

angular.module("myApp", ["ui.router"]).config(function($stateProvider){
    $stateProvider.state(stateName, stateConfig);
})

$stateProvider

$stateProvider.state(stateName, stateConfig)

Creates a new application state. For alternate usage, see Object-based States

The parameters for .state() are:

stateName

String

A unique state name, e.g. "home", "about", "contacts". To create a parent/child state use a dot, e.g. "about.sales", "home.newest". Read more about nested states: Nested States & Nested Views

// The state() method takes a unique stateName (String) and a stateConfig (Object)
$stateProvider.state(stateName, stateConfig);

// stateName can be a single top-level name (must be unique).
$stateProvider.state("home", {});

// Or it can be a nested state name. This state is a child of the above "home" state.
$stateProvider.state("home.newest", {});

// Nest states as deeply as needed.
$stateProvider.state("home.newest.abc.xyz.inception", {});

// state() returns $stateProvider, so you can chain state declarations.
$stateProvider.state("home", {}).state("about", {}).state("contacts", {});

stateConfig

Object

The stateConfig object has the following acceptable properties. This is just a reference, for usage and details please click the "Learn more..." links.

template, templateUrl, templateProvider

Three ways to set up your templates. Only use one per state (or view, see below)!

template String HTML content

templateUrl String URL path to template file OR Function, returns URL path string

templateProvider Function, returns HTML content string

Learn more about state templates

controller

A controller paired to the state

controller Function OR name as String

Learn more about controllers

resolve

A map of dependencies which should be injected into the controller

resolve Object

  • keys - name of dependency to be injected into controller
  • factory - {string|function} If string then it is alias for service. Otherwise if function, it is injected and return value it treated as dependency. If result is a promise, it is resolved before its value is injected into controller

Learn more about resolve

url

A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed.

url String

Learn more about url routing with states

params

An array of parameter names or regular expressions. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed.

params Array

Learn more about parameters (examples are shown in url form, but they work just the same here)

views

Use the views property to set up multiple views. If you don't need multiple views within a single state this property is not needed. Tip: remember that often nested views are more useful and powerful than multiple sibling views.

views Object

  • keys - {string} name of ui-view
  • view config - {object} view configuration object can set up its own templates, controllers and resolve data.

Learn more about multiple named views

abstract

An abstract state will never be directly activated, but can provide inherited properties to its common children states.

abstract Boolean - (default is false)

Learn more about abstract states

onEnter, onExit

Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog.

  • onEnter Function, injected including resolves
  • onExit Function, injected including resolves

Learn more about state callbacks

data

Arbitrary data object, useful for custom configuration.

data Object

Learn more about attaching custom data to states


$urlRouterProvider

$urlRouterProvider.when(whenPath, toPath)

Redirects from one url to another.

whenPath

String or RegExp or UrlMatcher

The incoming path that you want to redirect.

toPath

String

The path you want to redirect your user to.

Learn more about when()

$urlRouterProvider.otherwise(path)

Handles invalid routes by redirecting to the path provided.

path

String

The path you want to redirect your user to.

Learn more about otherwise()

$urlRouterProvider.rule(handler)

For custom url handling.

handler

Function

A function that takes in the $location as it's only argument. You are responsible for returning a valid path as a string.

Learn more about rule()


Directives

The following directives are provided by the ui.router module.

ui-view

The ui-view directive tells $state where to place your templates. A view can be unnamed or named.

<!-- Unnamed -->
<div ui-view></div> 

<!-- Named -->
<div ui-view="viewName"></div>

You can only have one unnamed view within any template (or root html). If you are only using a single view and it is unnamed then you can populate it like so:

<div ui-view></div> 
$stateProvider.state("home", {
    template: "<h1>HELLO!</h1>"
})

The above is equivalent to specifying your view explicity, by name, in this case an empty name:

$stateProvider.state("home", {
    views: {
        "": {
            template: "<h1>HELLO!</h1>"
        }
    }    
})

But typically you'll only use the views property if you name your view or have more than one view in the same template. There's not really a compelling reason to name a view if its the only one, but you could if you wanted, like so:

<div ui-view="main"></div> 
$stateProvider.state("home", {
    views: {
        "main": {
            template: "<h1>HELLO!</h1>"
        }
    }    
})

Really though, you'll use views to set up multiple views:

<div ui-view></div>
<div ui-view="chart"></div> 
<div ui-view="data"></div> 
$stateProvider.state("home", {
    views: {
        "": {
            template: "<h1>HELLO!</h1>"
        },
        "chart": {
            template: "<chart_thing/>"
        },
        "data": {
            template: "<data_thing/>"
        }
    }    
})

ui-sref

A directive that binds a link (<a> tag) to a state. If the state has an associated URL, the directive will automatically generate & update the href attribute via the $state.href() method. Clicking the link will trigger a state transition with optional parameters. Also middle-clicking, right-clicking, and ctrl-clicking on the link will be handled natively by the browser.

Usage:

  • ui-sref='stateName' - Navigate to state, no params. 'stateName' can be any valid absolute or relative state, following the same syntax rules as $state.go()
  • ui-sref='stateName({param: value, param: value})' - Navigate to state, with params.

Example:

Template HTML:

<a ui-sref="home">Home</a> | <a ui-sref="about">About</a>

<ul>
    <li ng-repeat="contact in contacts">
        <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
    </li>
</ul>

Generated HTML (Html5Mode Off results in prepended '#'):

<a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a>

<ul>
    <li ng-repeat="contact in contacts">
        <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
    </li>
    <li ng-repeat="contact in contacts">
        <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
    </li>
    <li ng-repeat="contact in contacts">
        <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
    </li>
</ul>

$state

$state.go(to [, toParams] [, options])

Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the current state.

to

String Absolute State Name or Relative State Path

The name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.

Some examples:

  • $state.go('contact.detail') will go to the 'contact.detail' state
  • $state.go('^') will go to a parent state.
  • $state.go('^.sibling') will go to a sibling state.
  • $state.go('.child.grandchild') will go to a grandchild state.

toParams

Object

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 currently defined parameters. This allows, for example, going to a sibling state that shares parameters specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. transitioning to a sibling will get you the parameters for all parents, transitioning to a child will get you all current parameters, etc.

options

Object

If Object is passed, object is an options hash. The following options are supported:

  • location Boolean (default true), If true will update the url in the location bar.
  • inherit Boolean (default true), If true will inherit url parameters from current url.
  • relative stateObject (default $state.$current), When transitioning with relative path (e.g '^'), defines which state to be relative from.

Examples Diagram:

  • Green = Starting State
  • Yellow = Intermediary State
  • Blue = Final Destination State

Enlarge

Go Examples

$state.transitionTo(to, toParams [, options])

Low-level method for transitioning to a new state. $state.go() uses transitionTo internally. $state.go() is recommended in most situations.

to

String

The name of the state that will be transitioned to.

toParams

Object

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

updateLocation or options

Boolean or Object

If Boolean is passed, then true (default) will update the url in the location bar.

If Object is passed, object is an options hash. The following options are supported:

  • location Boolean (default true), If true will update the url in the location bar.
  • inherit Boolean (default false), If true will inherit url parameters from current url.
  • relative stateObject (default null), When transitioning with relative path (e.g '^'), defines which state to be relative from.

$state.includes(stateName)

Returns Boolean

A method to determine if the current active state is equal to or is the child of the state stateName.

stateName

String

A partial name to be searched for within the current state name. For example, if you had the following states set up:

  • contacts
  • contacts.list
  • contacts.details
  • contacts.details.item
  • about

So, e.g. if you were within contacts.details.item then:

  • $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

$state.is(stateOrName)

Returns Boolean

Similar to includes, but only checks for the full state name.

stateOrName

String or Object

The state name or state object you'd like to check.

So, e.g. if you were within contact.details.item then:

$state.is("contact.details.item"); // returns true
$state.is(contactDetailItemStateConfigObj); // returns true
// Everything else would return false

$state.href(stateOrName [, params] [, options])

Returns String Compiled URL

A url generation method that returns the compiled url for the given state populated with the given params.

e.g. expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");

Note: returns null if no valid url can be constructed.

stateOrName

String or Object

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

params

Object

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

options

Object

An options hash, the following options are available:

  • lossy Boolean (default true) 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 navigable ancestor (aka ancestor with a valid url).
  • inherit Boolean (default false), If true will inherit url parameters from current url.
  • relative stateObject (default $state.$current), When transitioning with relative path (e.g '^'), defines which state to be relative from.

$state.get(stateName)

Note: May be getConfig depending on version.

Returns Object

A method for retrieving the configuration object for any state, by passing the name as a string.

stateName

String

The name of the state for which you'd like to get the original state configuration object for.

$state.current

Returns State Object

A reference to the state's config object. However you passed it in. Useful for accessing custom data.

Learn More about the state config object

Note: About using $state within a template

Since its very common to access $state in your templates, you need to bind $state to $rootScope (or any other accessible scope) to access it from a template/view. Typically you can do this on module run:

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

Now you can access state within a template:

<ul class="nav">
    <li ng-class="{ active: $state.includes('contacts') }"><a href="#/contacts">Contacts</a></li>
    <li ng-class="{ active: $state.includes('about') }"><a href="#/about">About</a></li>
</ul>

$stateParams

A service that is populated by the current state's parameters. Useful for injecting into your own controllers or services to access the parameters. It will have one key per url parameter.

Learn more about $stateParams


Events

State Change Events

All these events are fired at the $rootScope level.

  • $stateChangeSuccess - fired once the state transition is complete.
  • $stateChangeStart - fired when the transition begins.
  • $stateChangeError - fired when an error occurs during transition.
  • $viewContentLoaded - fired once per view when the view is loaded (after DOM is rendered)

Learn more about State Change Events

Clone this wiki locally