Tuesday, May 26, 2015

Defining routes using $routeProvider

In the previous post Routing in AngularJS we saw the benefits of routing in AngularJS, here we shall see an example of implementing Routing using AngularJS.

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.




Search Flipkart Products:
Flipkart.com

No comments: