Tuesday, July 7, 2015

$routeProvider service in AngularJS

The $routeProvider service plays an important role in enabling MVC framework in AngularJS, the $routeProvider allows us to define various routes and the view template to be bound to each of the route, additionally it also allows us to define the controller to be associated with each of the route/view. This way each of the embedded templates will be fully functional with each one having its own controller.

In the following example we shall see on how to implement Routing in AngularJS using $routeProvider

Main HTML Page with ng-view

The templates defined in the $routeProvider will be replaced in the location of the ng-view directive tag.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>AngularJS Routing example</title>
  </head>
  <body ng-app="sampleApp">
    <div>
          <div>
                   <div>
                             <a href="#ListContacts">List Contacts</a>  |
                             <a href="#AddContact">Add Contact</a>
                   </div>
                   <hr/>
                   <ng-view></ng-view>
          </div>
    </div>
          <script src="angular.min.js"></script>
          <script src="angular-route.min.js"></script>
          <script src="ContactsApp.js"></script>
  </body>
</html>

.js File with Route Configuration and Controller definition

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

sampleApp.config(function($routeProvider) {
    $routeProvider.
      when('/', {
          templateUrl: 'list_contact.html',
          controller: 'ListContactController'
      }).
      when('/ListContacts', {
          templateUrl: 'list_contact.html',
          controller: 'ListContactController'
      }).
      when('/AddContact', {
          templateUrl: 'new_contact.html',
          controller: 'AddContactController'
      }).
      otherwise({
          redirectTo: '/ListContacts'
      });
});

sampleApp.controller('AddContactController', function($scope) {
          $scope.title = 'Add Contact';
});

sampleApp.controller('ListContactController', function($scope) {
          $scope.title = 'List Contacts';
});

The $routeProvider defines 4 routes, ‘/’ points to the Root template, otherwise is the default routes, when the URL provided by the user does not match with any of the routes defined it will take this route.

There are 2 other routes /ListContacts & /AddContact which are defined with the .html template page and the Controller to be bound to these templates, these templates are fully functional views with their own Controllers, in fact they can point to different mode objects or make different $http ajax calls to populate the template, on a whole these are fully functional pages on their own.


Output:


Search Flipkart Products:
Flipkart.com

No comments: