AngularJS — Routing
Setup Routing
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
var app = angular.module('myApp', ['ngRoute']);
Route Configuration
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactController'
})
.otherwise({
redirectTo: '/'
});
});
Router Outlet
<a href="#!/home">Home</a>
<a href="#!/about">About</a>
<div ng-view></div>
Route Parameters
$routeProvider
.when('/user/:id', {
templateUrl: 'views/user.html',
controller: 'UserController'
});
app.controller('UserController', function($scope, $routeParams) {
$scope.userId = $routeParams.id;
});
Navigation
// Programmatic navigation
$location.path('/about');
// Go back
$window.history.back();
Mini Practice
- Set up routing
- Create route templates
- Use route parameters
- Navigate programmatically
Up Next
Continue with Templates — AngularJS templates.
Related Topics
Frequently Asked Questions about Routing
What is Routing in AngularJS?
Routing is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Routing?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Routing.
Why is Routing important in AngularJS?
Routing is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.