Tutorial

AngularJS Routing Example - ngRoute, $routeProvider

Published on August 4, 2022
author

By Meghna Gangwar

AngularJS Routing Example - ngRoute, $routeProvider

Today we will look into AngularJS Routing example using ngRoute module and $routeProvider. Earlier we looked into AngularJS Modules and AngularJS Controllers.

Routing in AngularJS

angularjs routing example, ngRoute, $routeProvider Routing in AngularJS is one of the core feature. In this AngularJS routing example, we will build a small single page application with multiple views to show you how routing in AngularJS works.

ngRoute

AngularJS ngRoute module provides routing, deep linking services and directives for angular applications. We have to download angular-route.js script that contains the ngRoute module from AngularJS official website to use the routing feature. You can also use the CDN in your application to include this file. In this tutorial, We are going to use the Google CDN. https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js If you are bundling this file into your application, then you can add it to your page with below code.

<script src="angular-route.js">

If you want to include it from Google CDN, then use below code.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>

Then load the ngRoute module in your AngularJS application by adding it as a dependent module as shown below.

angular.module('appName', ['ngRoute']);

ngView

ngView directive is used to display the HTML templates or views in the specified routes. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

$routeProvider

$routeProvider is used to configure the routes. We use the ngRoute config() to configure the $routeProvider. The config() takes a function which takes the $routeProvider as parameter and the routing configuration goes inside the function. $routeProvider has a simple API, accepting either the when() or otherwise() method.

AngularJS Routing Syntax

The following syntax is used to configure the routes in AngularJS.

var app = angular.module("appName", ['ngRoute']);

app.config(function($routeProvider) {
	$routeProvider
		.when('/view1', {
			templateUrl: 'view1.html',
			controller: 'FirstController'
		})
		.when('/view2', {
			templateUrl: 'view2.html',
			controller: 'SecondController'
		})
		.otherwise({
			redirectTo: '/view1'
		});
});

when() method takes a pathand a route as parameters. path is a part of the URL after the # symbol. route contains two properties - templateUrl and controller. templateUrl property defines which HTML template AngularJS should load and display inside the div with the ngView directive. controller property defines which controllers should be used with the HTML template. When the application is loaded, path is matched against the part of the URL after the # symbol. If no route paths matches the given URL the browser will be redirected to the path specified in the otherwise() function.

AngularJS Routing Example

Now let’s go through a simple example to understand the AngularJS rounting. At first, we will define a module, some routes, create controllers and create multiple views. Finally, we will create the shell page of our application to hold the multiple views.

  1. Create a module named mainApp and load ngRoute as a dependent module.
  2. Configure the routes using $routeProvider.
  3. We use two paths in the example, /home and /viewStudents.
  4. We use only a single controller in this example, StudentController
  5. StudentController is initialized with an array of students and a message. We will be showing the message in the home page and the students list in viewStudents page.
  6. Save this file as main.js

main.js

var mainApp = angular.module("mainApp", ['ngRoute']);

mainApp.config(function($routeProvider) {
	$routeProvider
		.when('/home', {
			templateUrl: 'home.html',
			controller: 'StudentController'
		})
		.when('/viewStudents', {
			templateUrl: 'viewStudents.html',
			controller: 'StudentController'
		})
		.otherwise({
			redirectTo: '/home'
		});
});

mainApp.controller('StudentController', function($scope) {
	$scope.students = [
		{name: 'Mark Waugh', city:'New York'},
		{name: 'Steve Jonathan', city:'London'},
		{name: 'John Marcus', city:'Paris'}
	];

	$scope.message = "Click on the hyper link to view the students list.";
});

For example, if the URL is like https://www.journaldev.com/index.html#/home, The URL part after the # matches /home, it will load home.html page and if it matches /viewStudents then it will load viewStudents.html in to the shell page. If nothing matches then it will go in otherwise condition and page will be redirected to home.html. Now we can create our views and save as home.html and viewStudents.html files. home.html

<div class="container">
	<h2> Welcome </h2>
	<p>{{message}}</p>
	<a href="#/viewStudents"> View Students List</a>
</div>

This is the default page of our application. In this view, we just print out the message, which we have already initialized in the StudentController. You can also see a link to the viewStudents page. viewStudents.html

<div class="container">
	<h2> View Students </h2>
	Search:
	<br/>
		<input type="text" ng-model="name" />
	<br/>
	<ul>
		<li ng-repeat="student in students | filter:name">{{student.name}} , {{student.city}}</li>
	</ul>

	<a href="#/home"> Back</a>
</div>

In the above view, you can see a list of students with a search option. Finally, follow below steps to complete our AngularJS routing example application.

  • ng-app auto-bootstraps our application mainApp
  • ngView directive is the placeholder of the views - home.html and viewStudents.html
  • Include angular.min.js and angular-route.min.js
  • Include main.js which we have created in the earlier steps.
  • Save the file as index.html

index.html

<!DOCTYPE html>
<html>
	<head lang="en">
	  <meta charset="utf-8">
	  <title>AngularJS Routing</title>

	</head>
	<body>

	  <div ng-app="mainApp">
		<ng-view></ng-view>
	  </div>

	  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
	  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
	  <script type="text/javascript" src="main.js"></script>
	</body>
</html>

That’s all for our AngularJS Routing example. Our application is ready to run.

Run your application

  • Save all the files in the same directory.
  • open index.html from your browser
  • Try our online demo.

AngularJS Routing Example Online Demo

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 17, 2015

the above code not working in IE 11 and chrome-41

- Ankur

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 14, 2015

The Google Chrome browser will not load local file by default due to security reason. You can set up a web server to test your applications or use Firefox. Please follow the following link for an alternate solution. https://www.chrome-allow-file-access-from-file.com/

- Jobin Bennett

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 16, 2017

Jobin, your solution may or may not work which depends on many factors. Universal solution for any browser running under any operating system is to run a local web server as described in my previous comment. Thank you very much. Best Regards, Anatoly S. Krivitsky, PhD in Computer Science

- Anatoly Krivitsky

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 12, 2015

    Great bhai this one i want thanks

    - sanjeev

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 26, 2015

      Hi, View Students List, how can i make above code in button (i.e) above code i want to write in button. can you please help me in getting that

      - laxman

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 26, 2015

        how can i implement using button , it is showing illegal character . can you please tell me it is quite urgent.

        - laxman

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 14, 2015

        Can you paste your code causing the error? I will try to cover all the scenarios in future posts. For now you can refer this link… https://stackoverflow.com/questions/15847726/is-there-a-simple-way-to-use-button-to-navigate-page-as-a-link-does-in-angularjs

        - Jobin Bennett

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 13, 2015

          it is a good tutorial, i learnt angularJS. thank you to this author.

          - kumaresan

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 23, 2015

            Nice article

            - Vasudha Desai

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              December 24, 2015

              very good article, one doubt, in the same exampe, how would make for to load in a div, other html file in home.html?, when i access index.html, directly home.html would have a div, that would loaded with other hmtl file.

              - Javier

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                February 4, 2016

                When I run this through eclipse, run on browser. This does not show any response. Blank page occurs. It appends #/home in output url but view is blank. What can be the probable issue. Other Tutorial on AngularJS pages loaded correctly. What can be the issue?

                - Vibhav

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 20, 2017

                did u get any solution? i am also facing the same issue

                - Harika.

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 7, 2017

                  i am getting same problem… (black page)

                  - mohammed

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    February 4, 2016

                    As discussed earlier also in comments, this is working only on mozilla due to security issue.

                    - Vibhav

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      February 26, 2016

                      This is very nice, sen of the ng-views - so simply presented. Thanks a lot, Very nice keep it up. - Ravi

                      - Ravi

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        March 31, 2016

                        this stuff is very helpful specially for me. i was several time fail to complete angular routing.so thank you

                        - Ajeet Singh

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          July 14, 2016

                          Thanks a lot Jobin, Your tutorial was a great help for me!

                          - mrad

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            September 1, 2016

                            I followed the same steps in eclipse but it does not show in eclipse browser.

                            - neeraj kumar

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            January 12, 2017

                            I am also facing same issue its not working.

                            - Manish Parganiha

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            September 14, 2017

                            Finally found the solution its mostly because the newer version of angular don’t support routing. Downgraded to v1.2.28 and it worked.

                            - Manish Parganiha

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              January 16, 2017

                              Here is what you may want to do (suppose you already have npm installed) 1. Install local web server like this: npm install -g -save-dev local-web-server 2. Within windows command line (or Linux/Unix/MAC bash window) go to directory with files from this article (in my case it is C:\Users\akriv\OneDrive\Documents\Angularjs router example, replace by your own as needed) 3. Run ws from above directory (just type ws!) 4. Point any of your browser (including but not limited to Chome) to https://127.0.0.1:8000/index.html Enjoy the functionality described in this article. Hope it will help. Best Regards, Anatoly S. Krivitsky, PhD in Computer Science

                              - Anatoly Krivitsky

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 7, 2017

                              i’m installed npm also globaly… still not working…

                              - mohammed

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                January 29, 2017

                                Thanks! for simple and good article

                                - Kranthi Kumar

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  June 30, 2017

                                  Thanks very helpfull can you do it for angular2 as well?

                                  - Mayur

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    July 29, 2017

                                    I am getting Object not found!

                                    - sandeep

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    April 12, 2018

                                    Thanks this is very useful for me

                                    - Naveena Ram

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      August 7, 2017

                                      Chrome does not allow this as templates are loaded via AJAX. You can resolve this issue by setting up a simple http server using npm. Go to your project folder in the nodejs command prompt. And type npm install http-server -g This will install http server on your machine. Then start your server using the command http-server Now, run your files using the ip and port on which your server has started and there you go! Routing works in Chrome as well.

                                      - mohammed sulaiman ben

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        December 1, 2017

                                        when I click on hyperlink View Students list ,it doesn’t work. Please help.

                                        - seema

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          November 9, 2018

                                          This is the best tutorial on ngroute i found on the internet… Please do same for UI-Router. With much regards

                                          - Kenny

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            November 12, 2018

                                            Thanks For The tutorial, Can we include the html pages by using any include tags in this above mentioned index.html page. because i want to include the different pages in menu bar. but the view of the included pages have be in the same index or menu bar page only… can we do that???

                                            - Mani Kiran

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              January 12, 2019

                                              This tutorial helped me a lot in understanding angularJS routes. Thank you.

                                              - Divyansh jain

                                                Join the Tech Talk
                                                Success! Thank you! Please check your email for further details.

                                                Please complete your information!

                                                Become a contributor for community

                                                Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                DigitalOcean Documentation

                                                Full documentation for every DigitalOcean product.

                                                Resources for startups and SMBs

                                                The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                Get our newsletter

                                                Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                New accounts only. By submitting your email you agree to our Privacy Policy

                                                The developer cloud

                                                Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                Get started for free

                                                Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                *This promotional offer applies to new accounts only.