Skip to content
timkindberg edited this page Feb 17, 2013 · 50 revisions

Main Goal

To evolve the concept of an Angular "Route" into a more general concept of a "State" for managing coarse application UI states.

Main Features:

  1. A state manager $stateProvider and $state, keeps state logic separate from routing logic.
  2. Nested states (parent/child relationships).
  3. Can set multiple views via named views. ui-view directive.
  4. URL Routing
  5. Backwards compatible with Angular v1 router
  6. Various other nuggets of goodness

State Manager

The new $stateProvider works similar to Angular's v1 router, but it focuses purely on state.

  • A state corresponds to a "place" in the application in terms of the overall UI and navigation.
  • A state describes (via the controller / template / view properties) what the UI looks like and does at that place.
  • States often have things in common, and the primary way of factoring out these commonalities in this model is via the state hierarchy, i.e. parent/child states aka nested states.

The simplest form of state

A state in its simplest form can be added like this (typically within module.config):

<!-- in index.html -->
<body ng-controller="MainCtrl">
<section ui-view></section>
</body>
// in app-states.js (or whatever you want to name it)
$stateProvider.state('contacts', {
  template: '<h1>My Contacts</h1>'
}

// main-controller.js
function MainCtrl($state){
  $state.transitionTo('contacts');
}

The template is automatically placed into the lone ui-view when the state is transitioned to.

Alternative ways to set the Template

Instead of writing the template inline you can load a partial. This is probably how you'll set templates most of the time.

$stateProvider.state('contacts', {
  templateUrl: 'contacts.html'
}

Or you can use a template provider function which can be injected and has access to locals, like this:

$stateProvider.state('contacts', {
  templateProvider: function ($timeout) {
    return $timeout(function () { return '<h1>My Contacts</h1>' }, 100);
  }
}

Controllers

You can pair a template with a controller like this:

$stateProvider.state('contacts', {
  template: '<h1>{{title}}</h1>',
  controller: function($scope){
    $scope.title = 'My Contacts';
  }
}

Resolve

You can use resolve to provide your controller with content or data that is custom to the state. This allows you to reuse controllers for similar objects that needs different dependencies.

$stateProvider.state('contacts', {
  template: '<h1>{{title}}</h1>',
  resolve: { title: 'My Contacts' },
  controller: function($scope, title){
    $scope.title = title;
  }
}

onEnter and onExit callbacks

There are also optional 'onEnter' and 'onExit' callbacks that get called when a state becomes active and inactive respectively. The callbacks also have access to all the resolved dependencies.

$stateProvider.state("contacts", {
  template: '<h1>{{title}}</h1>',
  controller: function($scope, title){
    $scope.title = 'My Contacts';
  },
  onEnter: function(..what to inject?...){
    ... need simple useful example here ...
  },
  onExit: function(..what to inject?...){
    ... need simple useful example here ...
  }
}

Nested states

States can be nested within each other. You can specify nesting in several ways:

You can use dot syntax to infer your heirarchy to the $stateProvider. Below, contacts.list becomes a child of contacts.

$stateProvider
  .state('contacts', {});
  .state('contacts.list', {});

Alternately, you can use specify the parent of a state via the parent property. IS THIS RIGHT?

$stateProvider
  .state('contacts', {});
  .state('list', {
    parent: 'contacts'
  });

Finally, if you aren't fond of using string-based states, you can also use object-based states, like this:

var states = {};
states.contacts = { 
    name: 'contacts',
    templateUrl: 'contacts.html'    
}
states.contacts.list = { 
    name: 'list',
    parent: states.contacts, //parent is required in this method
    templateUrl: 'contacts.list.html'
}

$stateProvider
  .state(states.contacts);
  .state(states.contacts.list)

If you use object-based states, you can usually reference the object directly when using other methods and property comparisons:

$state.transitionTo(states.contacts);
$state.self === states.contacts;
$state.includes(states.contacts)

Nested views

Child states will load their templates into their parent's ui-view.

$stateProvider
  .state('contacts', {
    templateUrl: 'contacts.html'
    controller: function($scope){
      $scope.contacts = [{ name: 'Alice' }, { name: 'Bob' }];
    }
  })
  .state('contacts.list', {
    templateUrl: 'contacts.list.html';
  });

function MainCtrl($state){
  $state.transitionTo('contacts.list');
}
<!-- index.html -->
<body ng-controller="MainCtrl">
  <div ui-view></div>
</body>
<!-- contacts.html -->
<h1>My Contacts</h1>
<div ui-view></div>
<!-- contacts.list.html -->
<ul>
  <li ng-repeat="contact in contacts">
    <a>{{contact.name}}</a>
  </li>
</ul>

Inheritance from parent states

When the application is in a particular State (aka when a state is "active"), all it's ancestor states are implicitly active as well. In the sample, when "contacts.list" state is active, the "contacts" state is implicitly active as well. Child states inherit views (templates/controllers) and resolved dependencies from parent state(s), which they can override.

Here contacts.list and contacts.detail are both inheriting the controller from contacts:

$stateProvider
  .state('contacts', {
    template: '<h1>My Contacts</h1>'
    controller: function($scope){
      $scope.contacts = [{ name: "Alice", favpet: "Mouse" }, 
                         { name: "Bob", favpet: "Python" }];
    }
  })
  .state('contacts.list', {
    template: '<ul><li ng-repeat="contact in contacts">' +
                 '<a ui-state-ref="contacts.detail">{{contact.name}}</a>' +
              '</li></ul>';
  })
  .state('contacts.detail', {
    template: "{contact.name}}'s favorite pet is {{contact.favpet}}";
  });

Multiple Named Views

You can name your views so that you can have more than one ui-view per state. Let's say you had an application state that needed to dynamically populate a graph, some table data and filters for the table like this: Multiple Named Views Mockup

When setting multiple views you need to use the views property on state. views is an object. The property keys on views should match your view names, like so:

<!-- somereportthing.html -->
<body>
  <div ui-view="filters"></div>
  <div ui-view="tabledata"></div>
  <div ui-view="graph"></div>
</body>
$stateProvider
  .state('report', {
    views: {
      'filters': { ... templates, controllers, resolve, etc ... },
      'tabledata': {},
      'graph': {},
    }
  })

Then each view in views is can set up its own templates, controllers, and resolve data.

$stateProvider
  .state('report',{
    views: {
      'filters': {
        templateUrl: 'report-filters.html',
        controller: function($scope){ ... controller stuff just for filters view ... }
      },
      'tabledata': {
        templateUrl: 'report-table.html',
        controller: function($scope){ ... controller stuff just for tabledata view ... }
      },
      'graph': {
        templateUrl: 'report-graph.html',
        controller: function($scope){ ... controller stuff just for graph view ... }
      },
    }
  })

Abstract States

An abstract state can have child states but can not get activated itself. An 'abstract' state is simply a state that can't be transitioned to, because it's simply there to provide some UI or dependencies that are common to it's child states.

Here is an example where the 'contacts' state is abstract. It's main purpose is to provide its child states with access to the $scope.contacts data. $scope.contacts will be available to both child state views for interpolation.

$stateProvider
    .state('contacts', {
        abstract: true,
        templateUrl: 'contacts.html',
        controller: function($scope){
            $scope.contacts = [{ name: "Alice" }, { name: "Bob" }];
    })
    .state('contacts.list', {
        templateUrl: 'contacts.list.html'
    })
    .state('contacts.detail', {
        templateUrl: 'contacts.detail.html'
    })

URL Routing

Most states in your application will probably have a url associated with them. URL Routing was not an after thought to the state mechanics, but was figured into the design from the beginning (all while keeping states separate from url routing)

Here's how you set a basic url.

$stateProvider
    .state('contacts', {
        url: "/contacts",
        templateUrl: 'contacts.html'
    })

Now when the user accesses index.html/contacts then the 'contacts' state would become active and the main ui-view will be populated with the 'contacts.html' partial. Alternatively, if the user were to transition to the 'contacts' state via transitionTo('contacts') then the url would be updated to index.html/contacts

Parameter Options

Write about all the various ways to add parameters (:, &, ?, etc)

Clone this wiki locally