Angular Routing with UI Router

Review

  • Controller

  • $scope

  • Services

  • Promises

SPA

(Single Page Application)

Routing

Non-SPA

Home

about.html

bio.html

products

.html

cart.html

Non-SPA

Routing

SPA

Router

about.html

bio.html

products

.html

cart.html

SPA

SPA

  • The URL bar isn't a path to a file
  • It describes a state
  • States can be nested

SPA

  • This is an amazon 'page'
  • URL bar can have metadata about a state
  • Product ID, etc.

SPA URL paths are fake!!!

  • Everything after # is hijacked by Angular
  • Cohort is a 'state' in Angular, not a file
  • The cohort id comes after the '/', gives instructions to angular to load a specific cohort

Benefits of routing

  • Shareable links (Deep linking)
  • Separation of concerns
  • More robust, complex applications

UI Router

The defacto routing solution for Angular

index.html

 <!-- Angular CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<!-- UI Router CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
    <!-- Apps -->
    <script src="app.js"></script>

app.js

angular.module('miniRouting', ['ui.router'])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('home', {
      templateUrl: 'home/home.html',
      controller: 'homeCtrl',
      url: '/'
    })
    .state('settings', {
      templateUrl: 'settings/settings.html',
      controller: 'settingsController',
      url: '/settings'
    })
    .state('product', {
      templateUrl: 'products/products.html',
      controller: 'productsController',
      url: '/products/:id'
    })

    $urlRouterProvider
      .otherwise('/');

});

Add 'ui.router' as a dependency

angular.module('miniRouting', ['ui.router'])

$stateProvider

angular.module('miniRouting', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('home', {
      templateUrl: 'home/home.html',
      controller: 'homeCtrl',
      url: '/'
    })
    .state('settings', {
      templateUrl: 'settings/settings.html',
      controller: 'settingsController',
      url: '/settings'
    })
    .state('product', {
      templateUrl: 'products/products.html',
      controller: 'productsController',
      url: '/products/:id'
    })

    $urlRouterProvider
      .otherwise('/');

});

$stateProvider

$stateProvider
    .state('home', {
      templateUrl: 'home/home.html',
      controller: 'homeCtrl',
      url: '/'
    })
    .state('settings', {
      templateUrl: 'settings/settings.html',
      controller: 'settingsController',
      url: '/settings'
    })
    .state('product', {
      templateUrl: 'products/products.html',
      controller: 'productsController',
      url: '/products/:id'
    })

Before we start

Install NPM

Install Live-Server

UI Router

By Brett Caudill

UI Router

  • 870