• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

AngularJS Routing Example using ngRoute

July 5, 2016 by javainterviewpoint Leave a Comment

In this article lets learn about a very useful and most used feature of AngularJS called Routing. AngularJS  routes enable us to implement multiple views in a Single Page Application(SPA). Usually in a Single Page Application we always want to avoid the reload of an entire page. We only want to load the relevant data and HTML snippet instead of fetching the entire HTML again and again. When we are using ngRoute of AngularJS the browser does not make any additional requests

AngularJS Route uses HashBang-ed URLs, For example a simple URL looks like http://www. AngularjsTutorial.com/first/page. Whereas In a Single Page AngularJS Application  the URL usually looks like, http://www. AngularjsTutorial.com/#/first/page. Browser treats URL with # differently than standard URL and hence an addition request will not be made to the server again.

ngRoute is Not Included by Default

The $routeProvider is defined in a module called ngRoute which is not present in the current version of angular.js. prior to AngularJS 1.1.6, the ngRoute module was used to be shipped out of the box. But all the subsequent versions don’t include ngRoute by default. That’s why we need to include additional angular-route.js

Lets take a quick look into AngularJs Route example before getting into the detailed explanation.

AngularJS Routing Example

<!DOCTYPE html>
<html ng-app="routingApp">
  <head>
    <title>AngularJS Routing</title>
    <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
   <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.js"></script>
  </head>
  <body>
    <ul>
     <li><a href="#/">Default Route</a></li>
     <li><a href="#/Spring">Spring</a></li>
     <li><a href="#/Angularjs">Angularjs</a></li>
     <li><a href="#/Unknown">Unknown</a></li>
   </ul>
   <div ng-view></div>

   <script type="text/javascript">
   angular
    .module('routingApp', [ 'ngRoute' ])
    .config([ '$routeProvider', function($routeProvider)
    {
      $routeProvider
        .when('/',
        {
           template : 'This is Default page'
        })
       .when('/Spring',
       {
          template : 'This is Spring page'
       })
       .when('/Angularjs',
       {
          template : 'This is Angularjs page'
       }).otherwise({
         redirectTo : '/'
      });
    }]);
   </script>
</body>
</html>
  1. As a first step we have included the Javascript file of the angular routing module (angular-routes.js)
  2. Now we need to add the ‘ngRoute’ as a dependency to our module before we perform anything using angular routes
  3. Next step is to define which place of the Single Page Application should change when the route changes, this can be done by defining the ‘ng-view’ directive.

         Note : There can be only one ng-view component per application, if we need more views to be defined then we need to go for ui-router.

4. Now We need define our routes in AngularJS config section using the $routeProvider. Angular Config consist of the function definition of the dependency which is injected. Our $routeProvider has two methods

         1. when(path, route)

                Path: The Path is a url or a URL regex specifies when this particular should be active
                Route : The second is the configuration object which specifies what needs to performed when the particular route is called.

        2.otherwise(params) : otherwise function on the $routeProvider specifies what AngularJS needs to do if the user tries to go to a URL that is not specified in the route configuration. You could see that we have added redirectTo key which redirects the unknown URL to the mentioned URL.

Output :

AngularJS Routing Example

Routing Configurations :

In the above code we saw a very simple route configuration. We simply loaded different templates for different route calls. The .when method $routeProvider can the below different options which can be specified.

$routeProvider.when(url, {
   template: string,
   templateUrl: string,
   controller: string, function or array,
   controllerAs: string,
   resolve: object<key, function>
});
  1. template: If the HTML which you want to display is not very large then it can be in-lined as a string to the template key. AngularJS directly inserts this template HTML into the ng-view directive.
  2. templateUrl: When the HTML is complex, we need to separate it into individual files and give the URL to the file in the templateUrl. AngularJS loads the separate file from the server which needs to be displayed for the particular route. One important thing is that for the first request only it loads the file from the server, further request are loaded from the local cache.
  3. controller: controller is an optional argument in .when function. It can be defined in two ways
    1. If we have already defined a controller using ng-controller, then we can just specify the name of the controller as a string.
    2. The other option is we can declare a controller in-line like below
$routeProvider.when('/Spring, {
  template: 'This is the Spring Page,
  controller: ['$log', function($log) {
    $log.log('Loading Spring Page!');
  }]
});
  1. controllerAs : controllerAs can be used when don’t want to name the controller using ‘as’ syntax. The below two route definitions are the same.
$routeProvider.when('/Spring’, {
  template: 'This is the Spring Page ',
  controller: 'SpringCtrl as ctrl'
});
$routeProvider.when('/Spring’, {
  template: 'This is the Spring Page ‘,
  controllerAs: 'ctrl'
});
  1. redirectTo : There are cases when the user keyed in the wrong url or page which got renamed we cannot show the user a 404 page instead we can redirect him to the index page in those cases we can use redirectTo option.
$routeProvider.when('/asdf', {
   redirectTo: ‘/index’
});

AngularJS $routeParams Example

There are times we need pass the parameter to the controller, for example we need to pass message or id in the URL which the controller uses for a Ajax call. Those parameters can be accessed by using the $routeParams. Let’s take the above AngularJS route example and pass a message to ‘Spring’ route.

<!DOCTYPE html>
<html ng-app="routingApp">
  <head>
    <title>AngularJS Routing</title>
    <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
    <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.js"></script>
  </head>
  <body ng-controller="routingCtrl">
   <ul>
     <li><a href="#/">Default Route</a></li>
     <li><a href="#/Spring/JavaInterviewPoint">Spring</a></li>
     <li><a href="#/Angularjs">Angularjs</a></li>
     <li><a href="#/Unknown">Unknown</a></li>
   </ul>
   <div ng-view></div>

   <script type="text/javascript">
    var app = angular .module('routingApp',['ngRoute']);
    app.config(function($routeProvider)
    {
      $routeProvider
       .when('/',
       {
          template : 'This is Default page',
          controller : 'routingCtrl'
       })
       .when('/Spring/:message',
       {
          templateUrl : 'app.html',
          controller : 'routingCtrl'
       })
       .when('/Angularjs',
       {
          template : 'This is Angularjs page'
       })
       .otherwise(
       {
          redirectTo : '/'
       });
    });
    app.controller('routingCtrl', function($routeParams,$scope) 
    {
       $scope.message = $routeParams.message;
    });
   </script>
  </body>
</html>

app.html

<!DOCTYPE html>
  <html>
   <head>
     <meta charset="ISO-8859-1">
     <title>Insert title here</title>
    </head>
    <body>
        <h1>Message Passed : "{{message }}"</h1>
    </body>
   </html>

In the above script we can see that we have added :message to the .when function and in the app.html we are displaying the message(we are passing ‘JavaInterviewPoint’ as the message). Once we hit on the Spring link we will be getting the below output.

AngularJS routeParams Example

Other interesting articles which you may like …

  • AngularJS Hello World Example
  • AngularJS – Modules and Controllers
  • Two-Way Data Binding in AngularJS Example
  • ngBind, ngBindHtml and ngBindTemplate
  • AngularJS Form Validation with ngMessages
  • AngularJS Spring MVC integration
  • AngularJS Spring MVC CRUD Example using $http service

Filed Under: AngularJS, J2EE, Java Tagged With: $routeParams, $routeProvider, AngularJS Route, AngularJS Routing Example, ngRoute

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·