Saturday 7 February 2015

Routing and multiple page view in AngularJS

Routing seems to bring the actual implementation of AngularJS.  In this article I have used four pages to be used inside the main page. The main page is index.html. Script page is app.js and four pages which is embedded with templateUrl are firstPage.html, secondPage.html, thirdPage.html and errorPage.html. Hyperlink has been created in index.html to navigate to first three pages and one errorPage.html to redirect if wrong page is called. I am adding code of all the files related to this project.

1. app.js

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

app.controller('MainCtrl',function($scope){

})

.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/', {
  template:'<h1>Welcome to my home page</h1>',
  controller:'MainCtrl'
  }).
  when('/firstPage', {
  templateUrl:'firstPage.html',
  controller:'MainCtrl'
  }).
  when('/secondPage', {
  templateUrl:'secondPage.html',
  controller:'MainCtrl'
  }).
  when('/thirdPage', {
  templateUrl:'thirdPage.html',
  controller:'MainCtrl'
  }).
  when('/errorPage', {
  templateUrl:'errorPage.html',
  controller:'MainCtrl'
  }).
  otherwise( {
  redirectTo : '/errorPage'
  });
}]);

2. index.html

<html ng-app="app">
  <head>
    <script src="angular.min.js"></script>
    <script src="angular-route.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainCtrl">
  <ul>
    <li><a href="#/firstPage">First Page</a></li>
    <li><a href="#/secondPage">Second Page</a></li>
    <li><a href="#/thirdPage">Third Page</a></li>
    <li><a href="#/">Back to Home</a></li>
  </ul>
  <div ng-view></div>
  </body>
</html>

3. firstPage.html

<html>
</body>
<h1>This is my first page</h1>
</body>
</html>

4. secondPage.html

<html>
</body>
<h1>I am onto my second page</h1>
</body>
</html>

5. thirdPage.html

<html>
</body>
<h1>I am at last in my last page</h1>
</body>
</html>

6. errorPage.html

<html>
</body>
<h1>You have entered a wrong parameter</h1>
</body>
</html>

No comments: