Working with URL Routing in AngularJS

Updated on     Kisan Patel

In this tutorial, we look into client-side routing with hashed URLs. Rather than including multiple templates in the view, we can break out the view into a layout and template views and only show the view we want to show based upon the URL the user is currently accessing.

Using the $routeProvider, we can take advantage of the browser’s history navigation and enable users to bookmark and share specific pages, as it uses the current URL location in the browser.

ngRoute module has not been include in the core of Angular file, we need to reference angular-route.js:

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

Lastly, we need to reference the ngRoute module as a dependency in our app module:

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

Now, create a layout and place the ng-view directive as the placeholder for the partials templates.

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

The route configuration is implemented using the config method:

myModule.config(function ($routeProvider) {

});

Now, to add a specific route, we can use the when method. This method takes two parameters (when(path, route)).

myModule.config(function ($routeProvider) {
      $routeProvider.when("/", {
               controller: "studentController",
               templateUrl: "/template/studentView1.html"
      });

      $routeProvider.when("/new", {
               controller: "studentController",
               templateUrl: "/template/studentView2.html"
      });

      $routeProvider.otherwise({ redirectTo: "/" });
});

Here, we set up route to render either the studentView1.html or the studentView2.html partial depending on the URL.

studentView1.html

<h1>This is the studentView1</h1>

studentView2.html

<h1>This is the studentView2</h1>

We can also set the controller property on the configuration object, the controller given will be associated with the new scope of the route.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AngularJS Routing Example</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/angular-route.min.js"></script>
</head>
<body>
    <div ng-app="myApp">
    <div ng-view="">
    </div>
</div>
</body>
</html>
<script type="text/javascript">
   var myModule = angular.module("myApp", ['ngRoute']);

   myModule.config(function ($routeProvider) {
      $routeProvider.when("/", {
          controller: "studentController",
          templateUrl: "/template/studentView1.html"
      });

      $routeProvider.when("/new", {
          controller: "studentController",
          templateUrl: "/template/studentView2.html"
      });

      $routeProvider.otherwise({ redirectTo: "/" });
   });

   myModule.controller('studentController', function ($scope) {
 
   });
</script>

The output will be:

route-demo1

route-demo2

Download Complete Source Code


AngularJS

Leave a Reply