📕
SEIRFX
  • Introduction
  • About These Notes
  • Schedule
  • Unit 2
    • Node
      • Internet Fundamentals
      • Full-Stack Fundamentals
      • Intro to Node
      • Node Modules
      • Node Packages
    • Express
      • Intro to Express
      • Routes
      • Routes Lab
      • Views
      • Templates
      • Layouts & Controllers
    • CRUD & REST
      • GET & POST
      • GET & POST Lab
      • PUT & DELETE
    • API Calls in Express
      • Axios
      • Request (no longer maintained)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
      • Objects Lesson
      • Objects quick guide
      • Object-ception
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Scope
      • Callbacks
      • Higher Order Functions
      • Callbacks Review Lab
      • Timing Functions
      • Iterators
      • Combining Data Types
      • Combining Data Types Lab
    • Javascript in the browser
      • DOM and Events
      • DOM Manipulation
      • DOM Review
      • DOM Review Lab
      • HP DOM Lab
      • Programmatic DOM Manipulation
      • Grids & Pyramids
      • DOM & Data
      • DOM Events
      • Color Palette Picker
      • Sketchpad
    • HTML5 Canvas
    • How To Reduce Redundancy
    • OOP
      • Westworld Lab
      • OOP Factories
      • OOP Inheritance
      • OOP Inheritance Lab
      • Tomagotchi Lab
      • OOP Space Battle
      • OOP Snowman
      • (2019) JavaScript OOP
      • (2016) OOP with Classes
      • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Left over Node/Express
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Being Successful in SEI
    • Internet Fundamentals
      • Internet Lab
    • Adjacent Workflow
      • UX/UI
      • Wireframing Exercise: Build an Idea
      • Agile
    • Post SEI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Objectives
  • Refactoring the Star Wars App
  • Using the AngularUI Router
  • Configuring Routes
  • Linking to routes
  • Wait, what's this prefix?
  • Passing URL Parameters
  • Programatically Navigating
  • Resources

Was this helpful?

  1. Archived Section
  2. AngularJS

Angular Routing

PreviousStar Wars CodealongNextAngular + Express

Last updated 4 years ago

Was this helpful?

Objectives

  • Incorporate an organized folder structure into an Angular app

  • Use a configuration block to add routing to an app

  • Retrieve route params from within a controller

  • Compare hashbang mode to HTML5 mode when configuring the router

Note, we'll be building upon the Star Wars app from the Angular Services codealong

Refactoring the Star Wars App

You'll probably notice soon that placing all of our controllers and services into app.js will soon become disorganized. So let's refactor the Star Wars app from earlier. Let's follow this layout.

- app
  - app.js
  - controllers.js
  - services.js
- views
- index.html

This will work for our examples in class, but for more complex apps, you will want to look at file structures that compartmentalize your app even more.

Now, let's move everything out of app.js so that we have three modules. We'll be injecting these modules like so:

  • inject ngResource into StarWarsServices

  • inject StarWarsServices into StarWarsCtrls

  • inject StarWarsCtrls into StarWarsApp

Whew! That's a lot of dependency injection. While beyond the scope of our Angular unit, injecting dependencies makes testing in Angular easier, because we can mock different dependencies if needed by defining test dependencies (this would be very useful for "faking" API calls).

app.js

angular.module('StarWarsApp', ['StarWarsCtrls'])

controllers.js

angular.module('StarWarsCtrls', ['StarWarsServices'])

// place your controllers down here

services.js

angular.module('StarWarsServices', ['ngResource'])

// place your services down here

Also, make sure to change and include those script files in index.html

<script src="app/app.js"></script>
<script src="app/services.js"></script>
<script src="app/controllers.js"></script>

Moving on, let's add routing to our app.

Using the AngularUI Router

We'll be using the popular ui.router module for routing our application.

The CDN link you'll need in index.html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>

You'll probably notice that this is a dependency, and it'll need to be injected into our app.

In app/app.js:

var app = angular.module('StarWarsApp', ['StarWarsCtrls', 'ui.router']);

And lastly, we'll need a way to switch out templates and controllers on our index page. For now, let's replace the contents of <body></body> with the following:

In index.html:

<body>
  <div class="container">
    <div ui-view></div>
  </div>
</body>

The ui-view directive will help complement our routes by including the template and controller of the current route. Whenever a route changes, the contents of ui-view are replaced with the new template and controller.

But we need routes! And controllers! And views! We already have the controller, so let's set up the view. In app/views, we'll create a template called films.html to list out all the films.

`app/views/films.html

<h1>Star Wars Films</h1>
<div class="well" ng-repeat="film in films">
  <h2>{{film.title}}</h2>
  <p>{{film.opening_crawl}}</p>
</div>

Configuring Routes

In app/app.js, let's add the following to the bottom of the file:

.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  //define routes
  $stateProvider
  .state('films', {
    url: '/',
    templateUrl: 'views/films.html',
    controller: 'FilmsCtrl'
  });

  //$locationProvider.html5Mode(false).hashPrefix('!');
}]);

Note: Run the app using a local HTTP server.

To add additional routes, just add additional state functions. Remember to define a controller (if necessary) for each page and create content in the related template files. Adding the otherwise condition is handy for redirecting invalid routes.

.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  //define routes
  $stateProvider
  .state('films', {
    url: '/',
    templateUrl: 'views/films.html',
    controller: 'FilmsCtrl'
  })
  .state('about', {
    url: '/about',
    templateUrl: 'views/about.html'
  });
}]);

Try it: Take a moment and implement a template for an about page.

Linking to routes

You can link to angular routes using <a> link tags

<a href="/#/about">About Page</a>

Wait, what's this prefix?

You'll see that Angular routes contain a "hashbang" prefix #. This is necessary in order to distinguish between front-end and back-end routes. A route like /about would end up being routed to a server, while Angular knows that /#/about is a front-end route.

We can configure our app to not use the "hashbang", but it will involve some configuration on the server. Specifically for Express, you would want all routes that aren't the root route (/) to send the back index.html.

Passing URL Parameters

Passing URL parameters with angular routes is similar to routes in Express or Rails. First we define a route with a parameter.

.state('showFilm', {
  url: '/films/:id',
  templateUrl: 'views/filmShow.html',
  controller: 'FilmShowCtrl'
})

Then, we can access the parameter in the controller using $stateParams (which must be injected into the controller). So let's add another controller in controllers.js for getting a specific film.

.controller('FilmShowCtrl', ['$scope', '$stateParams', 'Films', function($scope, $stateParams, Films) {
  $scope.film = {};

  Films.get({id: $stateParams.id}, function success(data) {
    $scope.film = data;
  }, function error(data) {
    console.log(data);
  });
}])

Now we need a filmShow.html file in the views folder:

<h1>{{film.title}}</h1>

<div class="well">
  <p>{{film.opening_crawl}}</p>
  <small>Release date: {{film.release_date}}</small>
</div>

<a href="/#/" class="btn btn-primary">&larr; Back</a>

...andddddd we need to add links to views/films.html

<h1>Star Wars Films</h1>

<div class="well" ng-repeat="film in films track by $index">
  <h2><a ng-href="/#/films/{{$index+1}}">{{film.title}}</a></h2>
</div>

Programatically Navigating

You can also cause the angular router to navigate to a new route using $state (another service).

.controller('FilmsCtrl', ['$scope', '$state', 'Films', function($scope, $state, Films) {
  // $scope.films = [];
  //
  // Films.query(function success(data) {
  //   $scope.films = data;
  // }, function error(data) {
  //   console.log(data);
  // });

  //this will redirect to a different state
  $state.go('about');
}])

This can also be used to get the current state, simply by leaving the parenthesis empty.

//returns the current angular state, complete with the URL, template, and controller
$state.current

Resources

    • The official Angular router, with less functionality than UI router

See this for more on this topic. We'll be implementing this configuration later on.

Note: Why do we use ng-href?

See this Scotch tutorial for details
StackOverflow response
Because Angular (see documentation)
Nested State in UI Router
ngRoute