Use routing in AngularJs

In a Single Page Application (SPA) routing is a important part. AngularJs also provide functions to make easy routing in our SPA. It helps us to,
  • Change the page without refreshing
  • Display different data on different pages
Lets see how to use AngularJs routing in our application to give a better user experience

Our simple app has a menu bar and when different tabs are clicked it should display different pages without refreshing the whole page. It should display list of employees only in home page.

Markup for Main page

<!DOCTYPE html>
<!-- define angular app -->
<html ng-app="myApp">
<head>  
  <!-- CDN for bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <!-- CDN for Angulat min and angular-route-->
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
  
</head>
<body>
  <nav class="navbar navbar-default">
    <div class="container">
      <div class="navbar-header">
        <a class="navbar-brand" href="/">SamplePage</a>
      </div>

      <ul class="nav navbar-nav navbar-left">
        <li><a href="#">Home</a></li>
        <li><a href="#about"> About</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
    </div>
  </nav>

  <div id="main">  
     <!-- this is where content will be injected -->
    <div ng-view></div>    
  </div>
  
  <footer class="text-center">   
    <p>View more tutorials on <a href="http://jascripts.blogspot.com/">Elegant JavaScript</a></p>
  </footer>
  <script src="script.js"></script>
</body>
</html>

Home Page

<div class="jumbotron text-center">
 <h1>{{ title }}</h1>
</div>
  <ul class="Employees">
        <li ng-repeat="name in names | orderBy:orderProp" class="thumbnail">
          <a href="#/employees/{{name.id}}" class="thumb"><img ng-src="{{name.imageUrl}}"></a>
          <a href="#/employees/{{name.id}}">{{name.name}}</a>          
        </li>
      </ul>

Contact and about page

<div class="jumbotron text-center">
 <h1>{{ title }}</h1>
</div>

Implement a main module for app

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

Angular's ngRoute module and contrlerModule created by us are used in this myApp module. contrlerModule contains the all controllers used in separate routes (Code for that module will shown latter part of the post).

Configure that module for routing

// configure routes
 myApp.config(function($routeProvider) {
  $routeProvider
   // route for the home page
   .when('/', {
    templateUrl : 'partials/home.html',
    controller  : 'mainController'
   })

   // route for the about page
   .when('/about', {
    templateUrl : 'partials/about.html',
    controller  : 'aboutController'
   })

   // route for the contact page
   .when('/contact', {
    templateUrl : 'partials/contact.html',
    controller  : 'contactController'
   });
 });


Using the myApp.config() method, we request the $routeProvider to be injected into our config function and use the $routeProvider.when() method to define our routes.

In this example routes are configured as when Angular app get the "/" that is root URL it will render the "home.html" page that is on partials folder with controller "mainController". In that way it configure templates and controllers for each route that is expected by application.

Create the separate module for controller which is dependency for main module

// create a seperate module for controllers
    var contrlerModule = angular.module('contrlerModule', []);

 // create the controller and inject Angular's $scope
 contrlerModule.controller('mainController', function($scope,$http) { 
        $scope.title = 'Home Page';
        $http.get('names.json').success(function(data) {
            $scope.names = data;
        });
        
        //$scope.orderProp="id";
 });

 contrlerModule.controller('aboutController', function($scope) {
  $scope.title = 'About Page';
 });

 contrlerModule.controller('contactController', function($scope) {
  $scope.title = 'Contact Page';
 });

In "mainController" it uses built in angular service "$http" and get a json object of employees from the server.
Setting all these parts together we can see a simple SPA which made with Angular routing.

No comments:

Post a Comment